如何使用html2canvas?
先上官方項目地址:
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", }) });}