简体   繁体   English

将画布数据保存到浏览器

[英]Save canvas data to browser

So I'm building a very simple drawing app with HTML5 canvas. 因此,我正在使用HTML5 canvas构建一个非常简单的绘图应用程序。

Basically, I want the user to be able to draw a line on the canvas, close the browser, come back, and the line is still there. 基本上,我希望用户能够在画布上画一条线,关闭浏览器,然后回来,并且该线仍然存在。

Is this possible? 这可能吗? I have found that you can save a canvas as an image, but would I be able to re-load that image back into a fresh canvas? 我发现您可以将画布另存为图像,但是我可以将该图像重新加载新的画布中吗?

I will try to explain to you doing my best. 我会尽力向您解释。 As you said, you can save the contents of the canvas as an image, but after you do with the image? 如您所说,您可以将画布的内容另存为图像,但是在处理完图像之后呢? For a fairly obvious security issue you can not save the image on the user's computer. 对于一个非常明显的安全问题,您无法将图像保存在用户的计算机上。 One method would be to create a server (for example in node.js to always use javascript) and when the user decides to save the drawing the image will be created, it will be sent to the server and it will be loaded into a database connected to the server. 一种方法是创建服务器(例如,在node.js中始终使用javascript),并且当用户决定保存图形时,将创建图像,该图像将被发送到服务器并将其加载到数据库中连接到服务器。 But this is a very complex solution, and is only useful in particular conditions, for example if you want the images to be exchanged between users of the app. 但这是一个非常复杂的解决方案,并且仅在特定条件下有用,例如,如果您希望在应用程序的用户之间交换图像。 For your case, and that of most people, it would be enough to save the drawing in the localstorage. 对于您以及大多数人而言,将图形保存在本地存储中就足够了。

What is HTML Web Storage? 什么是HTML Web存储? With web storage, web applications can store data locally within the user's browser. 借助Web存储,Web应用程序可以在用户的​​浏览器中本地存储数据。

With local storage you can save and read the variables that will remain in the browser. 使用本地存储,您可以保存和读取将保留在浏览器中的变量。 The value of the variables can only be strings, but no problem! 变量的值只能是字符串,但是没有问题! If you want for example (as in the small project below) to save in the local storage an objects or arrays you can convert them to a string json (if you do not know what is json look here: https://en.wikipedia.org/wiki/JSON and here https://www.digitalocean.com/community/tutorials/how-to-work-with-json-in-javascript ). 例如,如果您想要(例如在下面的小项目中)将对象或数组保存在本地存储中,则可以将它们转换为字符串json(如果您不知道json是什么,请看这里: https://en.wikipedia .org / wiki / JSON和此处https://www.digitalocean.com/community/tutorials/how-to-work-with-json-in-javascript )。 If you want to see the variables that the app saves, for google chrome open the console, go to the Appliaction tab, and you will find them local storage and session storage (another way to store data) In this small project we save an array of points that make up the drawing. 如果要查看应用程序保存的变量,请为Google chrome打开控制台,转到“应用程序”选项卡,然后您将找到它们的本地存储和会话存储(另一种存储数据的方式)。在这个小项目中,我们保存一个数组组成图形的点数。 For more information on localstorage here is the link: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage Remember, however, that not all browsers support local storage so this app for older browsers will not work, use chrome and you're okay! 有关本地存储的更多信息,请访问以下链接: https : //developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage但是记住,并非所有浏览器都支持本地存储,因此此应用程序适用于较旧的浏览器将无法正常工作,请使用chrome,您就可以了!

Html code: HTML代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>App to draw</title>

    <style>
        html,
        body {
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
            text-align: center;
            outline: 0;
        }

        #render {
            border: 5px solid rgba(120, 120, 129, 0.452);
            border-radius: 10px;
        }

        .container {
            position: absolute;
            left: 50%;
            top: 50%;
            -webkit-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
        }

        .button {
            border: 2px solid;
            border-radius: 10px;
            width: 100px;
            transition: .5s;
        }

        .save {
            border-color: #4CAF50;
            background-color: #4CAF50;
            color: white;
        }

        .save:hover {
            background-color: white;
            color: black;
        }

        .clear {

            border-color: #008CBA;
            background-color: #008CBA;
            color: white;
        }

        .clear:hover {
            background-color: white;
            color: black;
        }
    </style>
</head>

<body>
    <div class="container">
        <h3>Simple app for drawing made with 🧡 by Niccolo'</h3>
        <canvas id="render"></canvas>
        <div class="tools">
            <input type="button" class="button save" value="save" onclick="canvas.saveDrawing()">
            <input type="button" class="button clear" value="clear" onclick="canvas.clearDrawing()">
        </div>
    </div>

    <script src="sketch.js"></script>
</body>

</html>

Javascript code: JavaScript代码:

"use strict";

//mouse position
let mouseX,
  mouseY,
  isDragging = false;

//Canvas
class Canvas {
  constructor() {
    //html canvas
    this.canvas = document.getElementById("render");
    //context
    this.ctx = this.canvas.getContext("2d");
    //dimensions
    this.width = this.canvas.width = 300;
    this.height = this.canvas.height = 300;
    //Points that make up the simple design
    //He goes to look in the localstorage, if he does not find it he creates a simple array
    this.points = this.getDrawing() || [];
    //color
    this.color = "black";
    this.weight = 5;
  }

  update() {
    //If the user is dragging the mouse inside the canvas, he creates points
    if (isDragging) {
      if (
        mouseX >= 0 &&
        mouseX <= this.width &&
        mouseY >= 0 &&
        mouseY <= this.height
      ) {
        this.points.push({
          x: mouseX,
          y: mouseY
        });
      }
    }
  }
  draw() {
    //delete the background
    this.ctx.clearRect(0, 0, this.height, this.width);
    //set the color
    this.ctx.fillStyle = this.color;
    //draw points
    for (let point of this.points) {
      this.ctx.save();
      this.ctx.translate(point.x, point.y);
      this.ctx.beginPath();
      this.ctx.arc(0, 0, this.weight, 0, 2 * Math.PI, true);
      this.ctx.fill();
      this.ctx.restore();
    }
  }
  //save in the localstorage the points that make up the design
  saveDrawing() {
    const json = JSON.stringify(this.points);
    localStorage.setItem("drawing", json);
  }
  //search for points in the localstorage
  getDrawing() {
    return JSON.parse(localStorage.getItem("drawing"));
  }
  //clean the drawing pad
  clearDrawing() {
    this.points = [];
  }
}

//Canvas
const canvas = new Canvas();

//Events
window.addEventListener("mousemove", event => {
  let rect = canvas.canvas.getBoundingClientRect();
  mouseX = event.clientX - rect.left;
  mouseY = event.clientY - rect.top;
});
window.addEventListener("mousedown", () => (isDragging = true));
window.addEventListener("mouseup", () => (isDragging = false));

//main function in loop
function main() {
  canvas.update();
  canvas.draw();

  requestAnimationFrame(main);
}
//The program starts here
main();

Good luck with your project :-D 祝您项目顺利:-D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM