useCanvas.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * Shopro + qs-canvas 绘制海报
  3. * @version 1.0.0
  4. * @author lidongtony
  5. * @param {Object} options - 海报参数
  6. * @param {Object} vm - 自定义组件实例
  7. */
  8. import QSCanvas from 'qs-canvas';
  9. import {
  10. getPosterData
  11. } from './poster';
  12. export default async function useCanvas(options, vm) {
  13. const width = options.width;
  14. const qsc = new QSCanvas({
  15. canvasId: options.canvasId,
  16. width: options.width,
  17. height: options.height,
  18. setCanvasWH: (canvas) => {
  19. options.height = canvas.height;
  20. },
  21. },
  22. vm,
  23. );
  24. let drawer = getPosterData(options);
  25. // 绘制背景图
  26. const background = await qsc.drawImg({
  27. type: 'image',
  28. val: drawer.background,
  29. x: 0,
  30. y: 0,
  31. width,
  32. mode: 'widthFix',
  33. zIndex: 0,
  34. });
  35. await qsc.updateCanvasWH({
  36. width: background.width,
  37. height: background.bottom,
  38. });
  39. let list = drawer.list;
  40. for (let i = 0; i < list.length; i++) {
  41. let item = list[i];
  42. // console.log(item)
  43. // 绘制文字
  44. if (item.type === 'text') {
  45. await qsc.drawText(item);
  46. }
  47. // 绘制图片
  48. if (item.type === 'image') {
  49. if (item.d) {
  50. qsc.setCircle({
  51. x: item.x,
  52. y: item.y,
  53. d: item.d,
  54. clip: true,
  55. });
  56. }
  57. if (item.r) {
  58. qsc.setRect({
  59. x: item.x,
  60. y: item.y,
  61. height: item.height,
  62. width: item.width,
  63. r: item.r,
  64. clip: true,
  65. });
  66. }
  67. // console.log(item)
  68. try {
  69. await qsc.drawImg(item);
  70. } catch (error) {
  71. // console.log(error)
  72. }
  73. qsc.restore();
  74. }
  75. // 绘制二维码
  76. if (item.type === 'qrcode') {
  77. await qsc.drawQrCode(item);
  78. }
  79. }
  80. await qsc.draw();
  81. // 延迟执行, 防止不稳定
  82. setTimeout(async () => {
  83. options.src = await qsc.toImage();
  84. }, 100);
  85. return options;
  86. }