html2canvas截图苹果,html2canvas截图

本文介绍如何利用原生JavaScript结合html2canvas库将HTML内容转换为canvas,并进一步将canvas转为图片下载。内容包括设置CSS样式,处理图片资源,调用html2canvas生成canvas,以及实现图片的下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原生JS方法

引入html2canvas

http://html2canvas.hertzen.com/dist/html2canvas.min.js

html代码部分

html2canvas

*{

margin: 0;

padding: 0;

}

#htmlcanvas{

padding: 10px;

background: red;

height: 300px;

}

#ddd{

width: 100px;

height: 100px;

}

html内容

那一瞬间有一百万可能

canvas内容

保存

JS部分

var img = "https://qiniuimage.shengyaapp.com//H5/image/SQJZ/admin/listBtn.png";//imgurl 就是你的图片路径

function getBase64(imgUrl) {

return new Promise((resolve) => {

setTimeout(() => {

window.URL = window.URL || window.webkitURL;

var xhr = new XMLHttpRequest();

xhr.open("get", imgUrl, true);

// 至关重要

xhr.responseType = "blob";

xhr.onload = function () {

if (this.status == 200) {

//得到一个blob对象

var blob = this.response;

console.log("blob", blob)

// 至关重要

let oFileReader = new FileReader();

oFileReader.onloadend = function (e) {

let base64 = e.target.result;

document.getElementById("ddd").src = base64

html2canvas(document.querySelector("#htmlcanvas")).then(canvas => {

document.getElementById("canid").appendChild(canvas);

canvas.style.display = 'none';

});

console.log(document.getElementById("ddd").src)

};

oFileReader.readAsDataURL(blob);

}

}

xhr.send();

resolve()

}, 100);

})

}

document.getElementById("btn").onclick = function(){

getBase64(img).then(function(){

return xiazai()

})

}

function xiazai(){

return new Promise((resolve) => {

setTimeout(() => {

var strDataURI11;

var canv = document.getElementsByTagName("canvas")[0]

canv.crossOrigin = "anonymous"

var strDataURI = canv.toDataURL();

strDataURI11 = strDataURI

var blob=new Blob([''], {type:'application/octet-stream'});

var url = URL.createObjectURL(blob);

var a = document.createElement('a');

a.href = strDataURI11;

a.download = strDataURI11.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];

var e = document.createEvent('MouseEvents');

e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

a.dispatchEvent(e);

URL.revokeObjectURL(url);

document.getElementById("canid").innerHTML = ''

resolve()

},200);

})

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值