useCanvas.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 { getPosterData } from './poster';
  10. export default async function useCanvas(options, vm) {
  11. const width = options.width;
  12. const qsc = new QSCanvas(
  13. {
  14. canvasId: options.canvasId,
  15. width: options.width,
  16. height: options.height,
  17. setCanvasWH: (canvas) => {
  18. options.height = canvas.height;
  19. },
  20. },
  21. vm,
  22. );
  23. let drawer = getPosterData(options);
  24. // 绘制背景图
  25. const background = await qsc.drawImg({
  26. type: 'image',
  27. val: drawer.background,
  28. x: 0,
  29. y: 0,
  30. width,
  31. mode: 'widthFix',
  32. zIndex: 0,
  33. });
  34. await qsc.updateCanvasWH({
  35. width: background.width,
  36. height: background.bottom,
  37. });
  38. let list = drawer.list;
  39. for (let i = 0; i < list.length; i++) {
  40. let item = list[i];
  41. // 绘制文字
  42. if (item.type === 'text') {
  43. await qsc.drawText(item);
  44. }
  45. // 绘制图片
  46. if (item.type === 'image') {
  47. if (item.d) {
  48. qsc.setCircle({
  49. x: item.x,
  50. y: item.y,
  51. d: item.d,
  52. clip: true,
  53. });
  54. }
  55. if (item.r) {
  56. qsc.setRect({
  57. x: item.x,
  58. y: item.y,
  59. height: item.height,
  60. width: item.width,
  61. r: item.r,
  62. clip: true,
  63. });
  64. }
  65. await qsc.drawImg(item);
  66. qsc.restore();
  67. }
  68. // 绘制二维码
  69. if (item.type === 'qrcode') {
  70. await qsc.drawQrCode(item);
  71. }
  72. }
  73. await qsc.draw();
  74. // 延迟执行, 防止不稳定
  75. setTimeout(async () => {
  76. options.src = await qsc.toImage();
  77. }, 100);
  78. return options;
  79. }