你可以簡單地使用屏幕外的畫布上,您將吸引你的渲染畫布所需的偏移量。
這是一個快速書寫的功能,可能無法滿足所有要求,但至少可以給你一個想法: 請注意,它使用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;
});
}
而且由於stacksnippets®使用了一些強大的安全性在他們的框架調用它像
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
})
,我們不能讓一個現場演示在這裏,但你可以找到一個在這jsfiddle。
哦,對於那些想要ES5版本支持舊的html2canvas版本的人,你只需要在回調的回調中包裝裁剪功能,或者對於懶惰的回調,這裏是a fiddle。