您可以简单地使用屏幕外画布,您将在其上绘制具有所需偏移量的渲染画布。
这是一个快速编写的函数,它可能无法满足所有要求,但至少可以给你一个想法:
请注意,它使用 latest html2canvas version (0.5.0-beta4),它现在返回一个 Promise。
function screenshot(element, options = {}) {
// our cropping context
let cropper = document.createElement('canvas').getContext('2d');
// save the passed width and height
let finalWidth = options.width || window.innerWidth;
let finalHeight = options.height || window.innerHeight;
// update the options value so we can pass it to h2c
if (options.x) {
options.width = finalWidth + options.x;
}
if (options.y) {
options.height = finalHeight + options.y;
}
// chain h2c Promise
return html2canvas(element, options).then(c => {
// do our cropping
cropper.canvas.width = finalWidth;
cropper.canvas.height = finalHeight;
cropper.drawImage(c, -(+options.x || 0), -(+options.y || 0));
// return our canvas
return cropper.canvas;
});
}
然后这样称呼它
screenshot(yourElement, {
x: 20, // this are our custom x y properties
y: 20,
width: 150, // final width and height
height: 150,
useCORS: true // you can still pass default html2canvas options
}).then(canvas => {
//do whatever with the canvas
})
由于 stacksn-ps® 在其帧上使用了一些强大的安全性,我们无法在此处进行现场演示,但您可以在此 jsfiddle 中找到。
哦,对于那些想要支持旧 html2canvas 版本的 ES5 版本的人,您只需将裁剪功能包装在 onrendered 回调中,或者这里是 a fiddle 给懒惰的人。