HTML5 Canvas Stage Data URL Tutorial

How to get base64 string of the canvas?

To get the data URL of the stage with Konva, we can use the toDataURL()
method which requires a callback function for Stage (for other nodes callback is not required).
In addition, we can also pass in a mime type such as image/jpeg and a quality value that ranges between 0 and 1.
We can also get the data URLs of specific nodes, including layers, groups, and shapes.

Note: The toDataURL() method requires that any images drawn onto the canvas
are hosted on a web server with the same domain as the code executing it.
If this condition is not met, a SECURITY_ERR exception is thrown.

Instructions: Drag and drop the rectangle and then click on the save button to get the composite data url and open the resulting image in a new window

Konva Stage Data URL Demoview raw
<!DOCTYPE html>
<html>

<head>
<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Stage Data URL Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}

#buttons {
position: absolute;
top: 5px;
left: 10px;
}

#buttons>input {
padding: 10px;
display: block;
margin-top: 5px;
}
</style>
</head>

<body>
<div id="container"></div>
<div id="buttons">
<button id="save">
Save as image
</button>
</div>
<script>
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;

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);
stage.add(layer);

// function from https://stackoverflow.com/a/15832662/512042
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}

document.getElementById('save').addEventListener('click', function () {
var dataURL = stage.toDataURL();
downloadURI(dataURL, 'stage.png');
}, false);
</script>

</body>

</html>