保存savePic: function(){ var _this = this; var width = $('.picStyleMain')[._js canvas生成图片">
当前位置:   article > 正文

前端js根据html代码使用canvas生成图片_js canvas生成图片

js canvas生成图片

图片示例:实现点击保存下载弹窗内容生成图片

 

 html2canvas:html2canvas - Screenshots with JavaScript下载地址html2canvas:html2canvas - Screenshots with JavaScript

  1. 保存按钮事件: <i-button type="primary" @click="savePic" style="width: 100px">保存</i-button>
  2. savePic: function(){
  3. var _this = this;
  4. var width = $('.picStyleMain')[0].offsetWidth; //dom宽
  5. var height = $('.picStyleMain')[0].offsetHeight; //dom高
  6. var scale = 2;//放大倍数
  7. var canvas = document.createElement('canvas');
  8. canvas.width = width * 2;
  9. canvas.height = height * 2;
  10. canvas.style.width = width + 'px';
  11. canvas.style.height = height + 'px';
  12. var context = canvas.getContext('2d');
  13. context.scale(scale, scale);
  14. //设置context位置,值为相对于视窗的偏移量负值,让图片复位(解决偏移的重点)
  15. var rect = $('.picStyleMain').get(0).getBoundingClientRect();//获取元素相对于视察的偏移量
  16. context.translate(-rect.left, -rect.top);
  17. var opts = {
  18. imageTimeout: 15000,
  19. useCORS:true, //防止图片跨域
  20. x: 0,
  21. y: 0,
  22. scrollY: 0,
  23. scrollX: 0,
  24. logging: true,
  25. };
  26. var saveScroll = document.getElementsByClassName('ivu-modal-wrap')[3]
  27. saveScroll.scrollTop=0 //解决滚动条滑动时图片被遮挡问题
  28. html2canvas(document.querySelector(".picStyleMain"), opts).then((canvas) =>{
  29. var imgSrc = canvas.toDataURL('image/png')
  30. _this.canvasImg = imgSrc
  31. });
  32. let newName = this.applyNumber
  33. setTimeout(()=>{this.downloadImg(newName)},1000)
  34. },
  35. downloadImg(name) {
  36. let a = document.createElement('a') // 生成一个a元素
  37. a.style.display='none'
  38. let event = new MouseEvent('click') //创建一个单击事件
  39. a.download = name || 'photo' // 设置图片名称
  40. a.href= this.canvasImg
  41. a.dispatchEvent(event) //触发a的点击事件
  42. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/229258
推荐阅读
相关标签
  

闽ICP备14008679号