オフスクリーンキャンバスを使用すれば、レンダリングされたキャンバスを目的のオフセットで描画できます。
すべての要件を満たしていない可能性がありますが、少なくともあなたにアイデアを与えることができる、すぐに書かれた関数です: 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®がそのフレームにいくつかの強力なセキュリティを使用しているので、私たちはここでライブデモを作ることはできませんが、この内の1つを見つけることができる
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。
ああ、古いhtml2canvasバージョンをサポートしているES5バージョンを望む人は、onrenderedコールバックでクロッピング機能をラップするか、遅いコールバックの場合はa fiddleです。