1. 程式人生 > 其它 >在vue中將html頁面截圖並儲存成圖片或使用介面上傳file到後臺

在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 });
	},