在vue中将html页面截图并保存成图片或使用接口上传file到后台


安装并导入依赖

npm install --save html2canvas
import html2canvas from "html2canvas"

methods中定义

    toImage() {
      // 手动创建一个 canvas 标签
      const canvas = document.createElement("canvas");
      // 获取父标签,意思是这个标签内的 DOM 元素生成图片
      // lessonTableImg是给截图范围内的父级元素自定义的ref名称
      let canvasBox = this.$refs.lessonTableImg;
      // 获取父级的宽高
      const width = parseInt(window.getComputedStyle(canvasBox).width);
      const height = parseInt(window.getComputedStyle(canvasBox).height);
      // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
      canvas.width = width * 2;
      canvas.height = height * 2;
      canvas.style.width = width + "px";
      canvas.style.height = height + "px";
      const context = canvas.getContext("2d");
      context.scale(2, 2);
      const options = {
        backgroundColor: "#061b48",  //设置canvas背景图颜色 防止有些图片透明
        canvas: canvas,
        useCORS: true,
      };
      html2canvas(canvasBox, options).then((canvas) => {
        console.log(canvas);
        // toDataURL 图片格式转成 base64
        let dataURL = canvas.toDataURL("image/png");
        //调用下载
        // this.downloadImage(dataURL);
        // 转为file文件
        var file = this.dataURLtoFile(dataURL, "封面");
        var formdata = new FormData();
        formdata.append("file", file);
	//file上传到后台
        upImgResource(formdata).then((res) => {
          if (res.code == 0) {
            console.log(res);
          }
        });
      });
    },

如果需要下载图片可以直接使用base64下载


		//下载图片 传入base64
		downloadImage(url) {
		  // 如果是在网页中可以直接创建一个 a 标签直接下载
		  let a = document.createElement("a");
		  a.href = url;
		  a.download = "首页截图";
		  a.click();
		},
		//base64转file方法
		dataURLtoFile: function (dataurl, filename) {
		  var arr = dataurl.split(","),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		  while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		  }
		  return new File([u8arr], filename + ".png", { type: mime });
		},

♥ 如果本章内容为您提供了帮助 请点击推荐哦


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM