背景介绍:工作中需要用到这个库,实现一个页面自定义的业务需求。由于对于这个库 html2canvas 还不太熟悉,便单独建了一个简单的 vue 工程,写一个简单的 demo,熟悉一下该库的用法……

demo 最终效果演示:
demo.gif

参考资料

源码

  1. <template>
  2. <div id="app">
  3. <div ref="test-container" class="container">
  4. <div class="box" style="background: red">A</div>
  5. <div class="box" style="background: green">B</div>
  6. <div class="box" style="background: blue">C</div>
  7. <div class="box" style="background: orange">D</div>
  8. </div>
  9. <div class="img-container">
  10. <span class="icon" @click="createNewCanvas(index - 1)"></span>
  11. <img :src="screenShotSrc" alt="" class="test-img" />
  12. <span class="icon" @click="createNewCanvas(index + 1)"></span>
  13. </div>
  14. </div>
  15. </template>
  16. <script>
  17. import html2canvas from "html2canvas";
  18. export default {
  19. name: "App",
  20. data() {
  21. return {
  22. screenShotSrc: "",
  23. index: 0,
  24. isCreating: false,
  25. duration: 3000,
  26. timer: null,
  27. };
  28. },
  29. mounted() {
  30. this.createNewCanvas();
  31. this.timer = setTimeout(() => {
  32. this.createNewCanvas(this.index + 1);
  33. }, this.duration); // 开启 - 自动轮播
  34. },
  35. methods: {
  36. // 产生一张截图
  37. async createNewCanvas(index = 0) {
  38. if (this.isCreating) return; // 上一张截图还没创建完毕
  39. console.log("暂停");
  40. clearTimeout(this.timer); // 暂停 - 自动轮播
  41. this.isCreating = true;
  42. this.index = (index + 4) % 4;
  43. const canvas = await html2canvas(this.$refs["test-container"], {
  44. // 截图区域
  45. x: this.index * 100,
  46. y: 0,
  47. width: 100,
  48. height: 100,
  49. // 跨域问题
  50. allowTaint: false,
  51. useCORS: true,
  52. // 解决 - 截图模糊问题
  53. // dpi: 300,
  54. // scale: 4,
  55. // backgroundColor: "#f40", // => default transparent
  56. });
  57. this.screenShotSrc = canvas.toDataURL("image/png");
  58. this.isCreating = false;
  59. this.timer = setTimeout(() => {
  60. this.createNewCanvas(this.index + 1);
  61. }, this.duration); // 开启 - 自动轮播
  62. },
  63. },
  64. };
  65. </script>
  66. <style lang="less" scoped>
  67. #app {
  68. display: flex;
  69. justify-content: space-around;
  70. align-items: center;
  71. flex-direction: column;
  72. height: 300px;
  73. }
  74. .container {
  75. display: flex;
  76. .box {
  77. width: 100px;
  78. height: 100px;
  79. line-height: 100px;
  80. border-radius: 5px;
  81. text-align: center;
  82. color: #fff;
  83. font-size: 2rem;
  84. }
  85. }
  86. .img-container {
  87. display: flex;
  88. height: 100px;
  89. align-items: center;
  90. .icon {
  91. font-size: 1.5rem;
  92. cursor: pointer;
  93. }
  94. .test-img {
  95. height: 100px;
  96. width: 100px;
  97. border: 1px solid #ddd;
  98. margin: 0 2rem;
  99. }
  100. }
  101. </style>