前言

uniapp绘制朋友圈海报分享图片

实现

  1. <canvas class="my-canvas" canvas-id="shareCanvas"></canvas>
  1. import Painter from "mp-painter";
  2. let painter = new Painter(uni.createCanvasContext('shareCanvas', this));
  3. return new Promise((resolve,reject) => {
  4. painter.draw({
  5. type: "container",
  6. top: 0,
  7. left: 0,
  8. children: [
  9. {type: "rect", top: 0, width: 610, height: 970, background: "#fff"}
  10. ]
  11. }).then(() => {
  12. Promise.all([
  13. painter.draw({
  14. type: "container",
  15. top: 40,
  16. left: 210,
  17. children: [
  18. {type: "image", top: 0, left: 0, width: 40, height: 40, src: "http://cdn.zsdx.cn/student-app/images/hand-logo.png"},
  19. ]
  20. }),
  21. painter.draw({}),
  22. ...
  23. ]).then(resp => {
  24. //把指定画布内容倒醋和指定大小的图片
  25. uni.canvasToTempFilePath( {
  26. canvasId: 'shareCanvas',
  27. quality: 0.01,
  28. success: res => {
  29. console.log('tempFilePath', resp.tempFilePath);
  30. },
  31. fail: error => {
  32. reject(error);
  33. }
  34. },this);
  35. })
  36. })
  37. })

API

注: 位置和宽高根据实际情况填写.

  1. //绘制图片
  2. painter.draw({
  3. type: "container",
  4. top: x,
  5. left: y,
  6. children: [
  7. {type: "image", top: 0, left: 0, width: 40, height: 40, src: "http://cdn.zsdx.cn/student-app/images/hand-logo.png"},
  8. ]
  9. })
  10. //绘制文本
  11. painter.draw({
  12. type: "container",
  13. top: x,
  14. left: y,
  15. children: [
  16. { type: "text", top: 0, left: 0,fontSize: 30,baseline: "middle", content: "掌上大学" }
  17. ]
  18. })
  19. //绘制矩形
  20. painter.draw({
  21. type: "container",
  22. top: x,
  23. left: y,
  24. children: [
  25. {type: "rect", top: 0, left:0, width: 530, height: 530, background: '#FF2A2A'}
  26. ]
  27. })
  28. //矩形圆角渐变色
  29. painter.draw({
  30. type: "container",
  31. top: x,
  32. left: y,
  33. children: [
  34. {type: "rect", top: 449, left: margin_price_1-104 - 70, width: 530 - (margin_price_1-104-70), height: 80, background: {
  35. type: "liner-gradient",
  36. x1: 0, y1: 0, x2: 280, y2: 80,
  37. colorStops: [
  38. { offset: 0, color: "#FF4978" },
  39. { offset: 1, color: "#FF2A2A" }
  40. ]
  41. }, borderRadius: [200, 0, 0, 0], position: "absolute"}
  42. ]
  43. })
  44. //多行文本
  45. painter.draw({
  46. type: "container",
  47. top: 670,
  48. left: 40,
  49. children: [
  50. {
  51. type: "text-block",
  52. top: 0,
  53. left: 0,
  54. width: 346,
  55. lineClamp: 2,
  56. fontSize: 28,
  57. color: '#1D2023',
  58. content: '多行文本多行文本多行文本多行文本多行文本多行文本多行文本多行文本多行文本',
  59. }
  60. ]
  61. })

参考

https://github.com/xlfsummer/mp-painter

相关

https://github.com/quanweiwang/uniapp-canvas-drawer