JS将div转为图片,base64、Blob、File类型

JS将div转为图片,base64、Blob、File类型

html2canvas(document.getElementById("preview"), {
        // width: 30, //截图宽度
        // height: 50, //截图高度
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色(null)
        useCORS: true, //支持图片跨域
        scale: 1, //设置放大的倍数
    }).then((canvas) => {
        let url = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64
        let blob=toBlob(url);//封装toBlob方法,转为blob类型
        var file = new File([blob], "123", {type: "image/png", lastModified: Date.now()});//转为File类型
        let blobUrl=URL.createObjectURL(file);
        console.log(blob)
        console.log(file)
        console.log(blobUrl)

        // let a = document.createElement("a");
        // a.href=url;
        // a.download="123"
        // a.click();
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码将 base64 字符串换为 Blob 对象: ```javascript // 将 base64 字符串换为 Blob 对象 function base64ToBlob(base64Str) { const parts = base64Str.split(';base64,'); const contentType = parts[0].split(':')[1]; const raw = window.atob(parts[1]); const rawLength = raw.length; const uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); } ``` 在 Vue 中,可以在组件的方法中调用该函数,例如: ```vue <template> <div> <input type="file" ref="fileInput" @change="handleFileChange"> </div> </template> <script> export default { methods: { handleFileChange() { const file = this.$refs.fileInput.files[0]; const reader = new FileReader(); reader.onload = () => { const base64Str = reader.result; const blob = this.base64ToBlob(base64Str); console.log(blob); // 在这里可以将 blob 对象上传到服务器或者进行其他操作 }; reader.readAsDataURL(file); }, // 将 base64 字符串换为 Blob 对象 base64ToBlob(base64Str) { const parts = base64Str.split(';base64,'); const contentType = parts[0].split(':')[1]; const raw = window.atob(parts[1]); const rawLength = raw.length; const uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }, }, }; </script> ``` 在上述代码中,我们首先使用 `<input type="file">` 元素让用户选择文件,并在 `handleFileChange` 方法中读取文件内容并将其换为 base64 字符串。然后,我们调用 `base64ToBlob` 方法将 base64 字符串换为 Blob 对象,并可以将其上传到服务器或者进行其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值