如何使用html2canvas?
发布网友
发布时间:2023-11-29 23:21
我来回答
共1个回答
热心网友
时间:2024-01-17 23:46
先上官方项目地址:html2canvas
第一步:html转为canvas
基于html2canvas.js可将一个元素渲染为canvas,只需要简单的调用html2canvas(element[, options]);即可。下列html2canvas方法会返回一个包含有<canvas>元素的promise:
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
第二步:canvas转image
上一步生成的canvas即为包含目标元素的<canvas>元素对象。实现保存图片的目标只需要将canvas转image即可。
使用第三方库Canvas2Image.js,调用其convertToImage方法。Canvas2Image.js
下面是一个完整的例子:
convert2canvas() {
var shareContent = YourTargetElem;
var width = shareContent.offsetWidth;
var height = shareContent.offsetHeight;
var canvas = document.createElement("canvas");
var scale = 2;
canvas.width = width * scale;
canvas.height = height * scale;
canvas.getContext("2d").scale(scale, scale);
var opts = {
scale: scale,
canvas: canvas,
logging: true,
width: width,
height: height
};
html2canvas(shareContent, opts).then(function (canvas) {
var context = canvas.getContext('2d');
var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
document.body.appendChild(img);
$(img).css({
"width": canvas.width / 2 + "px",
"height": canvas.height / 2 + "px",
})
});
}