html2canvas - 如何定义顶部,左侧,底部,右侧有自动裁剪?
问题描述:
我有一页1280x768。以下代码正在制作1280x768全屏快照,但我需要忽略顶部10px,左侧10px,底部10px,右侧10px。html2canvas - 如何定义顶部,左侧,底部,右侧有自动裁剪?
您可以在document.body.appendChild(canvas);
之前或之后做那个作物/比例尺吗?使用CSS3或JS左右?
window.takeScreenShot = function() {
html2canvas(document.getElementById("top"), {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
width:1280,
height:768
});
};
答
你可以简单地使用屏幕外的画布上,您将吸引你的渲染画布所需的偏移量。
这是一个快速书写的功能,可能无法满足所有要求,但至少可以给你一个想法: 请注意,它使用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。