Reputation: 3698
I am using KonvaJS in my project. I need to save the stage/canvas
as an image(it would be great if exported image is high resolution image). KonvaJS
has a function called stage.toDataURL() which returns canvas content as a Base64 string. The challenge with this function is that it only returns visible area of the canvas. I need to export entire canvas as image not only it's visible area. I tried with Canvas2Image but it is also saving only visible area not full canvas. Is there any way I can achieve it? Here's a plunkr to play with some poc(proof of concept) code.
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var rectX = stage.getWidth() / 2 - 50;
var rectY = stage.getHeight() / 2 - 25;
(function() {
for (var i = 0; i < 50; i++) {
layer.add(new Konva.Rect({
x: i * 50,
y: 0,
width: 50,
height: 10000,
fill: Konva.Util.getRandomColor()
}));
}
})();
var box = new Konva.Rect({
x: rectX,
y: rectY,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
box.on('mouseover', function() {
document.body.style.cursor = 'pointer';
});
box.on('mouseout', function() {
document.body.style.cursor = 'default';
});
layer.add(box);
layer.draw();
stage.add(layer);
function exportCanvas() {
var dataURL = stage.toDataURL();
window.open(dataURL);
}
document.getElementById('save').addEventListener('click', exportCanvas, false);
Upvotes: 0
Views: 2339
Reputation: 20373
The best way to achieve this is to resize stage before export, then resize it back:
var oldSize = stage.size();
var exportSize = {
width: 3000,
height: 3000
};
stage.size(exportSize);
stage.draw();
var dataURL = stage.toDataURL(exportSize);
stage.size(oldSize);
stage.draw();
Demo: http://plnkr.co/edit/DiqsE7rZdDx3JIAyJZQK?p=preview
Upvotes: 5