I want to make it so that when I press the save button, file explorer opens and opts me to choose location to save the JSON file of the canvas. I also want to be able to load the canvas with the JSON file via the load button. How can I get started with this? Any help is appreciated.
Advertisement
Answer
I hope this is what you are trying to achieve:
JavaScript
x
54
54
1
var canvas = document.querySelector('canvas')
2
var ctx = canvas.getContext('2d');
3
var reader = new FileReader();
4
5
// generates a random RGB color string
6
var randomColor = function () {
7
return `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
8
}
9
10
// draw something on the canvas
11
ctx.fillStyle = randomColor();
12
ctx.fillRect(Math.random() * 100, 100, 100, Math.random() * 150);
13
ctx.fillStyle = randomColor();
14
ctx.fillRect(Math.random() * 200, Math.random() * 50, Math.random() * 150, 200);
15
16
// event handler for the save button
17
document.getElementById('save').addEventListener('click', function () {
18
// retrieve the canvas data
19
var canvasContents = canvas.toDataURL(); // a data URL of the current canvas image
20
var data = { image: canvasContents, date: Date.now() };
21
var string = JSON.stringify(data);
22
23
// create a blob object representing the data as a JSON string
24
var file = new Blob([string], {
25
type: 'application/json'
26
});
27
28
// trigger a click event on an <a> tag to open the file explorer
29
var a = document.createElement('a');
30
a.href = URL.createObjectURL(file);
31
a.download = 'data.json';
32
document.body.appendChild(a);
33
a.click();
34
document.body.removeChild(a);
35
});
36
37
// event handler for the load button
38
document.getElementById('load').addEventListener('change', function () {
39
if (this.files[0]) {
40
// read the contents of the first file in the <input type="file">
41
reader.readAsText(this.files[0]);
42
}
43
});
44
45
// this function executes when the contents of the file have been fetched
46
reader.onload = function () {
47
var data = JSON.parse(reader.result);
48
var image = new Image();
49
image.onload = function () {
50
ctx.clearRect(0, 0, canvas.width, canvas.height);
51
ctx.drawImage(image, 0, 0); // draw the new image to the screen
52
}
53
image.src = data.image; // data.image contains the data URL
54
};
JavaScript
1
3
1
<canvas height="300" width="300"></canvas>
2
<div><button id="save">Save</button></div>
3
<div>Load: <input type="file" id="load"></div>