【问题标题】:Saving canvas to JSON and loading JSON to canvas将画布保存到 JSON 并将 JSON 加载到画布
【发布时间】:2017-06-28 15:30:24
【问题描述】:

我想这样当我按下保存按钮时,文件资源管理器会打开并选择我选择位置来保存画布的 JSON 文件。我还希望能够通过加载按钮加载带有 JSON 文件的画布。我该如何开始呢?任何帮助表示赞赏。

【问题讨论】:

  • 这是 JSFiddle:jsfiddle.net/zyywx6h5 我不知道如何让 javascript 处理这个问题,但这个想法来自布局
  • 必须是 JSON 吗?为什么不将其存储为图像?
  • 因为他想保存画布的状态以备后用。图像无法做到这一点。
  • 我正在使用它来练习对 json 对象的操作。我只是不知道该怎么做

标签: javascript json html canvas


【解决方案1】:

我希望这是你想要达到的目标:

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

// generates a random RGB color string
var 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 button
document.getElementById('save').addEventListener('click', function () {
  // retrieve the canvas data
  var canvasContents = canvas.toDataURL(); // a data URL of the current canvas image
  var data = { image: canvasContents, date: Date.now() };
  var string = JSON.stringify(data);

  // create a blob object representing the data as a JSON string
  var file = new Blob([string], {
    type: 'application/json'
  });
  
  // trigger a click event on an <a> tag to open the file explorer
  var 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 button
document.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 = new Image();
  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
};
<canvas height="300" width="300"></canvas>
<div><button id="save">Save</button></div>
<div>Load: <input type="file" id="load"></div>

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2015-05-23
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2013-07-26
    相关资源
    最近更新 更多