useCanvas.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 = await getPosterData(options);
  25. // console.log("drawer",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. await qsc.updateCanvasWH({
  37. width: background.width,
  38. height: background.bottom,
  39. });
  40. let list = drawer.list;
  41. for (let i = 0; i < list.length; i++) {
  42. let item = list[i];
  43. // 绘制文字
  44. if (item.type === 'text') {
  45. console.log(item)
  46. await qsc.drawText(item);
  47. }
  48. // 绘制图片
  49. if (item.type === 'image') {
  50. if (item.d) {
  51. qsc.setCircle({
  52. x: item.x,
  53. y: item.y,
  54. d: item.d,
  55. clip: true,
  56. });
  57. }
  58. if (item.r) {
  59. qsc.setRect({
  60. x: item.x,
  61. y: item.y,
  62. height: item.height,
  63. width: item.width,
  64. r: item.r,
  65. clip: true,
  66. });
  67. }
  68. try {
  69. await qsc.drawImg(item);
  70. } catch (error) {
  71. console.log(error)
  72. }
  73. qsc.restore();
  74. }
  75. // 绘制矩形
  76. if (item.type === 'rect') {
  77. if (item.r) {
  78. qsc.setRect({
  79. x: item.x,
  80. y: item.y,
  81. height: item.height,
  82. width: item.width,
  83. r: item.r,
  84. clip: true,
  85. });
  86. }
  87. try {
  88. await qsc.draw(item);
  89. } catch (error) {
  90. console.log(error)
  91. }
  92. qsc.restore();
  93. }
  94. // 绘制二维码
  95. if (item.type === 'qrcode') {
  96. console.log(item)
  97. await qsc.drawQrCode(item);
  98. }
  99. }
  100. await qsc.draw();
  101. // 延迟执行, 防止不稳定
  102. setTimeout(async () => {
  103. options.src = await qsc.toImage();
  104. }, 100);
  105. return options;
  106. }