在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