useCanvas.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * 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. console.log(drawer)
  26. // 绘制背景图
  27. const background = await qsc.drawImg({
  28. type: 'image',
  29. val: drawer.background,
  30. x: 0,
  31. y: 0,
  32. width,
  33. mode: 'widthFix',
  34. zIndex: 0,
  35. });
  36. // const background = await qsc.drawImg({
  37. // "name": "avatar",
  38. // "type": "image",
  39. // "val": "https://file.sheepjs.com/static/img/shop/goods/share.png",
  40. // "x": 14.040000000000001,
  41. // "y": 14.040000000000001,
  42. // "width": 49.14000000000001,
  43. // "height": 49.14000000000001,
  44. // "d": 49.14000000000001
  45. // });
  46. await qsc.updateCanvasWH({
  47. width: background.width,
  48. height: background.bottom,
  49. });
  50. let list = drawer.list;
  51. for (let i = 0; i < list.length; i++) {
  52. let item = list[i];
  53. console.log(item)
  54. // 绘制文字
  55. if (item.type === 'text') {
  56. await qsc.drawText(item);
  57. }
  58. // 绘制图片
  59. if (item.type === 'image') {
  60. if (item.d) {
  61. qsc.setCircle({
  62. x: item.x,
  63. y: item.y,
  64. d: item.d,
  65. clip: true,
  66. });
  67. }
  68. if (item.r) {
  69. qsc.setRect({
  70. x: item.x,
  71. y: item.y,
  72. height: item.height,
  73. width: item.width,
  74. r: item.r,
  75. clip: true,
  76. });
  77. }
  78. try {
  79. await qsc.drawImg(item);
  80. } catch (error) {
  81. console.log(error)
  82. }
  83. qsc.restore();
  84. }
  85. // 绘制二维码
  86. if (item.type === 'qrcode') {
  87. await qsc.drawQrCode(item);
  88. }
  89. }
  90. await qsc.draw();
  91. // 延迟执行, 防止不稳定
  92. setTimeout(async () => {
  93. options.src = await qsc.toImage();
  94. }, 100);
  95. return options;
  96. }