网页截图,html2canvas简单示例
<div id="box"> <p>asd4a5s6fa6s5f1asf</p> <img style="width:200px" src="xxxxxx.png" /> <button style="width:100px;height:30px" onclick="prtsc()">prtsc</button> </div> <script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.js"></script> <script> function prtsc() { html2canvas(document.getElementById('box'), { allowTaint: true, useCORS: true, }).then(canvas => { dataURL = canvas.toDataURL("image/png"); var img = new Image(); img.src = dataURL; img.onload = function () { document.getElementById('box').after(img); } }); } </script>
图片需要在后端配置允许跨域,否则不会显示
或者可以将图像src转为base64,可以解决一部分跨域问题
$(function () {
$("img").each(function () {
var imgDOM = $(this);
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img.setAttribute('crossOrigin', 'anonymous')
img.crossOrigin = '';
img.src = $('#img').attr('src');
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL('image/png');
imgDOM.attr('src', dataURL);
canvas = null;
}
})
})