html2canvas 生成一个 base64 的海报

let html2canvas = null;

export default {
  beforeMount() {
    import('html2canvas').then((plugin) => {
      html2canvas = plugin.default;
    });
  },
  methods: {
    // 获取分享图片 base64
    getShareImgBase64() {
      return new Promise((resolve) => {
        setTimeout(() => {
          // #capture 就是我们要获取截图对应的 DOM 元素选择器
          html2canvas(document.querySelector('#capture'), {
            useCORS: true, // 【重要】开启跨域配置
            scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
            allowTaint: true, // 允许跨域图片
          }).then((canvas) => {
            const imgData = canvas.toDataURL('image/jpeg', 1.0);
            resolve(imgData);
          });
        }, 300); // 这里加上 300ms 的延迟是为了让 DOM 元素完全渲染完成后再进行图片的生成
      });
    },
  },
};
function downloadImage(base64Url) {
    let imgUrl = base64Url;
    if (window.navigator.msSaveOrOpenBlob) {//兼容IE浏览器的写法
	    let imageStr = atob(imgUrl.split(",")[1]);
	    let n = imageStr.length;
	    let u8arr = new Uint8Array(n);
	    while (n--) {
	    u8arr[n] = imageStr.charCodeAt(n);
	    }
	    let blob = new Blob([u8arr]);
	    window.navigator.msSaveOrOpenBlob(blob, "chart-download" + "." + "png");
	} else {//非IE浏览器
		let a = document.createElement("a");
		a.href = imgUrl;
		a.setAttribute("download", "chart-download");
		a.click();
	}
}
posted @ 2023-11-24 13:29  东八区  阅读(51)  评论(0编辑  收藏  举报