html2canvas官网:
GitHub:

使用html2canvas

安装依赖:

  1. yarn add html2canvas

在Vue中的使用示例:

  1. <template>
  2. <div class="canvas-app">
  3. <!-- canvas原内容 -->
  4. <div class="canvas-content">
  5. <div class="canvas-content-text">这是文本内容</div>
  6. </div>
  7. <!-- 按钮 -->
  8. <div class="canvas-btns">
  9. <div @click="generatorCanvas">生成海报</div>
  10. </div>
  11. <!-- canvas生成弹窗 -->
  12. <div class="canvas-wrap">
  13. <div class="canvas-wrap-img">
  14. <img :src="imgUrl" alt="">
  15. </div>
  16. <div class="canvas-wrap-content"></div>
  17. </div>
  18. </div>
  19. </template>
  20. <script>
  21. import html2canvas from 'html2canvas';
  22. export default {
  23. data() {
  24. return {
  25. imgUrl: ''
  26. }
  27. },
  28. methods: {
  29. generatorCanvas() {
  30. let ele = document.querySelector('.canvas-content')
  31. html2canvas(ele, {
  32. backgroundColor: "#ffffff",
  33. allowTaint: true, //开启跨域
  34. useCORS: true,
  35. scrollY: 0,
  36. scrollX: 0,
  37. }).then(canvas => {
  38. let wrap = document.querySelector('.canvas-wrap-content')
  39. wrap.appendChild(canvas);
  40. this.imgUrl = canvas.toDataURL('image/png');
  41. // debugger
  42. });
  43. }
  44. }
  45. };
  46. </script>
  47. <style>
  48. .canvas-content {
  49. height: 50px;
  50. background-color: #0f0;
  51. }
  52. .canvas-content-text {
  53. color: red;
  54. }
  55. </style>

生成后的DOM结构:
Snipaste_2022-04-14_09-54-02.png

图片跨域问题

如果是同源的图片路径,像这种,生成海报图片是正常的:

  1. <div class="canvas-content">
  2. <div class="canvas-content-text">这是文本内容</div>
  3. <div>
  4. <img src="/favicon.png" width="100" height="100" alt="">
  5. </div>
  6. </div>

如果是非同源的图片路径,生成海报将报错:

  1. <div class="canvas-content">
  2. <div class="canvas-content-text">这是文本内容</div>
  3. <div>
  4. <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">
  5. </div>
  6. </div>

点击“生成海报”报跨域问题:
Snipaste_2022-04-14_10-12-43.png

解决方案有两种,都需要服务端支持。

方法一:服务器设置静态资源响应头 Access-Control-Allow-Origin*或者域名白名单,然后在img标签添加crossorigin="anonymous"属性。

  1. <img crossorigin=“anonymous” src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">

方法二:使用代理服务器获取资源。参考:

参考资料