index.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export default {
  2. name: 'painter',
  3. handle: (dp, option) => {
  4. dp.canvas.width = option.width;
  5. dp.canvas.height = option.height;
  6. dp.draw(async (ctx) => {
  7. for (let i = 0; i < option.contents.length; i++) {
  8. ctx.save();
  9. const drawInfo = option.contents[i];
  10. const { left = 0, top = 0 } = drawInfo;
  11. if (drawInfo.type === 'rect') {
  12. ctx.fillStyle = drawInfo.background || '#000000';
  13. ctx.fillRoundRect(left, top, drawInfo.width, drawInfo.height, drawInfo.radius || 0);
  14. }
  15. if (drawInfo.type === 'image') {
  16. await ctx.drawImageFit(drawInfo.src, {
  17. objectFit: drawInfo.objectFit || 'cover',
  18. intrinsicPosition: drawInfo.position || ['center', 'center'],
  19. specifiedPosition: [left, top],
  20. specifiedSize: {
  21. width: drawInfo.width,
  22. height: drawInfo.height
  23. },
  24. radius: drawInfo.radius
  25. });
  26. }
  27. if (drawInfo.type === 'text') {
  28. ctx.fillStyle = drawInfo.color || '#000000';
  29. ctx.font = `\
  30. ${drawInfo.fontStyle || 'normal'} \
  31. ${drawInfo.fontWeight || 'normal'} \
  32. ${drawInfo.fontSize || 30} \
  33. ${drawInfo.fontFamily || 'serial'}\
  34. `;
  35. ctx.fillText(drawInfo.content, left, top, drawInfo.width);
  36. }
  37. if (drawInfo.type === 'line-feed-text') {
  38. ctx.fillStyle = drawInfo.color || '#000000';
  39. ctx.font = `\
  40. ${drawInfo.fontStyle || 'normal'} \
  41. ${drawInfo.fontWeight || 'normal'} \
  42. ${drawInfo.fontSize || 30} \
  43. ${drawInfo.fontFamily || 'serial'}\
  44. `;
  45. ctx.fillWarpText({
  46. x: drawInfo.left,
  47. y: drawInfo.top,
  48. layer: drawInfo.lineClamp,
  49. lineHeight: drawInfo.lineHeight,
  50. maxWidth: drawInfo.width,
  51. text: drawInfo.content
  52. });
  53. }
  54. if (drawInfo.type === 'qr-code') {
  55. if (typeof ctx.drawQrCode !== 'function') {
  56. console.error('--- 当前未引入qr-code扩展, 将自动省略该二维码绘制 ---');
  57. return false;
  58. }
  59. ctx.drawQrCode({
  60. x: left,
  61. y: top,
  62. size: drawInfo.size,
  63. text: drawInfo.content,
  64. margin: drawInfo.margin || 5,
  65. backgroundColor: drawInfo.backgroundColor || '#ffffff',
  66. foregroundColor: drawInfo.foregroundColor || '#000000',
  67. });
  68. }
  69. ctx.restore();
  70. }
  71. });
  72. }
  73. };