引入JS<script src="http://www.duanlonglong.com/link/gaoqing/html2canvas.js"></script>或<script src="http://www.duanlonglong.com/link/gaoqing/html2canvas.min.js"></script>
用我的记得引入JQ哦,jquery
以下是从demo里粘过来的,TargetNode为要生成图片的DIV,将谁生成图片就将谁的ID设为TargetNode。 canvas.toDataURL("image/jpeg")为图片本地临时路径,将$('.img')里面的img改成自己的img标签的类名。
$("#downpdf").on("click", function() {
var canvas2 = document.createElement("canvas");
let _canvas = document.querySelector('#TargetNode');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
//可以按照自己的需求,对context的参数修改,translate指的是偏移量
var context = canvas2.getContext("2d");
context.scale(2, 2);
html2canvas(document.querySelector('#TargetNode'), {
canvas: canvas2
}).then(function(canvas) {
pic = canvas;
console.log(pic.toDataURL())
$('.img').attr('src', canvas.toDataURL("image/jpeg"));
});
});