Skip to content Skip to sidebar Skip to footer

Saving Canvas To Json And Loading Json To Canvas

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 c

Solution 1:

I hope this is what you are trying to achieve:

var canvas = document.querySelector('canvas')
var ctx = canvas.getContext('2d');
var reader = newFileReader();

// generates a random RGB color stringvar randomColor = function () {
  return`rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
}

// draw something on the canvas
ctx.fillStyle = randomColor();
ctx.fillRect(Math.random() * 100, 100, 100, Math.random() * 150);
ctx.fillStyle = randomColor();
ctx.fillRect(Math.random() * 200, Math.random() * 50, Math.random() * 150, 200);

// event handler for the save buttondocument.getElementById('save').addEventListener('click', function () {
  // retrieve the canvas datavar canvasContents = canvas.toDataURL(); // a data URL of the current canvas imagevar data = { image: canvasContents, date: Date.now() };
  var string = JSON.stringify(data);

  // create a blob object representing the data as a JSON stringvar file = newBlob([string], {
    type: 'application/json'
  });
  
  // trigger a click event on an <a> tag to open the file explorervar a = document.createElement('a');
  a.href = URL.createObjectURL(file);
  a.download = 'data.json';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
});

// event handler for the load buttondocument.getElementById('load').addEventListener('change', function () {
  if (this.files[0]) {
    // read the contents of the first file in the <input type="file">
    reader.readAsText(this.files[0]);
  }
});

// this function executes when the contents of the file have been fetched
reader.onload = function () {
  var data = JSON.parse(reader.result);
  var image = newImage();
  image.onload = function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(image, 0, 0); // draw the new image to the screen
  }
  image.src = data.image; // data.image contains the data URL
};
<canvasheight="300"width="300"></canvas><div><buttonid="save">Save</button></div><div>Load: <inputtype="file"id="load"></div>

Post a Comment for "Saving Canvas To Json And Loading Json To Canvas"