微信h5页面canvas画图,并用a便签下载,由于微信限制,所以只能是长按保存图片

H5之canvas画图,下载,借用html2canvas插件

DPR() { // 获取设备的屏幕尺寸
      if (window.devicePixelRatio && window.devicePixelRatio > 1) {
        return window.devicePixelRatio;
      }
      return 1;
    },
    parseValue(value) { // 转换参数为number类型
      return parseInt(value, 10);
    },
    async drawCanvas (selector) { // canvas画图
      // 获取想要转换的 DOM 节点
      const dom = document.querySelector(selector);
      const box = window.getComputedStyle(dom);
      // DOM 节点计算后宽高
      const width = this.parseValue(box.width);
      const height = this.parseValue(box.height);
      // 获取像素比
      const scaleBy = this.DPR();
      // 创建自定义 canvas 元素
      var canvas = document.createElement('canvas');
      // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
      canvas.width = width * scaleBy;
      canvas.height = height * scaleBy;
      // 设定 canvas css宽高为 DOM 节点宽高
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      // 获取画笔
      const context = canvas.getContext('2d');
      // 将所有绘制内容放大像素比倍
      context.scale(scaleBy, scaleBy);
      let x = width
      let y = height
      // console.log(x,y)
      return await html2canvas(dom, {canvas}).then(() => {
        this.convertCanvasToImage(canvas, x ,y)
      })
    },
    // 生成图片并插入到dom中
     convertCanvasToImage(canvas, x, y) {
      let image = new Image();
      // let _container = document.getElementsByClassName('poptip_1')[0].firstChild
      let _container = document.getElementById('save-img').firstChild
      // console.log(_container)
      // return
      let _body = document.getElementById('save-img')
      image.width = x;
      image.height = y;
      image.src = canvas.toDataURL("image/png")
      this.canvasImgUrl = canvas.toDataURL("image/png")
      // let nodesList = document.getElementById('save-img').childNodes
      if (_container) {
        _body.removeChild(_container)
      }
      document.getElementById('save-img').appendChild(image)
      this.$store.dispatch('hideLoading')
      // document.getElementById('save-img').insertBefore(image,document.getElementById('save-img-c'))
      return image;
    },
    //模拟a标签下载
saveImgToLocal () {
      const save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      save_link.href = this.canvasImgUrl // 画好后的base64图片,从convertCanvasToImage方法得到的,不能太大了,应该是不能超过10万字符,超过了,就下载失败了
      save_link.download = 'JDGJEnglishTest.png' // 自定义图片的名字
      const event = document.createEvent('MouseEvents')
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      save_link.dispatchEvent(event)
    },

你可能感兴趣的:(html,vue,canvas,HTMLcanvas)