I have a page 1280x768. following code is making 1280x768 full page snapshot, but i need to ignore from top 10px, from left 10px from bottom 10px, from right 10px.
Can you do that crop/scale or so before or after document.body.appendChild(canvas);
? using CSS3 or JS or so?
window.takeScreenShot = function() {
html2canvas(document.getElementById("top"), {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
width:1280,
height:768
});
};
I have a page 1280x768. following code is making 1280x768 full page snapshot, but i need to ignore from top 10px, from left 10px from bottom 10px, from right 10px.
Can you do that crop/scale or so before or after document.body.appendChild(canvas);
? using CSS3 or JS or so?
window.takeScreenShot = function() {
html2canvas(document.getElementById("top"), {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
width:1280,
height:768
});
};
Share
Improve this question
edited Dec 17, 2016 at 3:53
Kaiido
138k14 gold badges260 silver badges325 bronze badges
asked Dec 16, 2016 at 23:50
user285594user285594
1 Answer
Reset to default 4You can simply use an offscreen canvas, on which you will draw your rendered canvas with the desired offset.
Here is a quickly written function which may not fulfill all requirements, but which can at least give you an idea : note that it uses latest html2canvas version (0.5.0-beta4), which now returns a 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;
});
}
And call it like that
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
})
Since stacksnippets® uses some strong security on their frames, we can't make a live demo in here, but you can find one in this jsfiddle.
Oh and for those who want an ES5 version supporting the old html2canvas version, you just have to wrap the cropping function in the onrendered callback, or here is a fiddle for the lazy ones.