How to save the specified view as a picture in the uni-app development H5 project

How to save the specified view as a picture in the uni-app development H5 project

  1. install dependencies
安装这两个依赖
    "html2canvas": "^1.4.1",
    "image-tools": "^1.4.0",
npm安装命令:
	npm -i -s html2canvas image-tools
  1. Code implementation
    The code is implemented using vue, where imageWrapper1 is the ref on the view tag, for example:
    insert image description here
    js code:
	toImage() {
      uni.showLoading({
        title: '加载中'
      });
      html2canvas(this.$refs.imageWrapper1.$el).then(canvas => {
        let dataURL = canvas.toDataURL("image/png");
        base64ToPath(dataURL).then(path => {
          this.saveHeadImgFile(path, 'test1.png')
          uni.hideLoading();
        })
      });
    },
    saveHeadImgFile(domImg, filename) {
      // 创建隐藏的可下载链接
      let eleLink = document.createElement('a');
      eleLink.href = domImg;
      eleLink.download = filename;
      eleLink.style.display = 'none';
      // 触发点击
      document.body.appendChild(eleLink);
      eleLink.click();
      // 然后移除
      document.body.removeChild(eleLink);
    }
  1. Just call this.toImage() when needed
  2. Notice:
    • If multiple calls are required, in order to avoid interference during execution, you can modify the code
      Method 1: Give each a tag a new id, and delete the a tag according to the id
      Method 2: Use the setTimeout function to delay execution (not necessarily safe )
      Method 3: After the first execution ends, call the method in the callback function to download the next picture
    • The requested network image may not be able to be intercepted, please contact me if you have a solution, the current solution is to directly put the background image in the static directory

Guess you like

Origin blog.csdn.net/geshi201028/article/details/123822535