【问题标题】:Save canvas data to browser将画布数据保存到浏览器
【发布时间】:2018-08-23 05:29:45
【问题描述】:

所以我正在使用 HTML5 画布构建一个非常简单的绘图应用程序。

基本上,我希望用户能够在画布上画一条线,关闭浏览器,再回来,这条线还在。

这可能吗?我发现您可以将画布另存为图像,但我能否将该图像重新加载回到新的画布中?

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    我会尽力向您解释。 如您所说,您可以将画布的内容保存为图像,但是在使用图像之后呢?对于一个相当明显的安全问题,您不能将图像保存在用户的计算机上。一种方法是创建一个服务器(例如在 node.js 中始终使用 javascript),当用户决定保存绘图时,将创建图像,它将被发送到服务器并将其加载到数据库中连接到服务器。但这是一个非常复杂的解决方案,并且仅在特定条件下有用,例如,如果您希望在应用程序的用户之间交换图像。对于您和大多数人的情况,将绘图保存在本地存储中就足够了。

    什么是 HTML 网络存储? 借助 Web 存储,Web 应用程序可以在用户浏览器中本地存储数据。

    使用本地存储,您可以保存和读取将保留在浏览器中的变量。 变量的值只能是字符串,但没问题! 例如,如果您想(如下面的小项目)将对象或数组保存在本地存储中,您可以将它们转换为字符串 json(如果您不知道什么是 json,请看这里:https://en.wikipedia.org/wiki/JSON 和这里 @987654322 @)。 如果您想查看应用程序保存的变量,对于谷歌浏览器打开控制台,转到应用程序选项卡,您会发现它们是本地存储和会话存储(另一种存储数据的方式) 在这个小项目中,我们保存了一组构成绘图的点。有关本地存储的更多信息,请点击以下链接:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage 但是请记住,并非所有浏览器都支持本地存储,因此这个适用于旧版浏览器的应用程序将无法运行,使用 chrome 就可以了!

    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 代码:

    "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();
    

    祝你的项目好运:-D

    【讨论】:

    • 这是我得到的最详细的答案之一,非常感谢!我不知道我怎么没想到要保存实际绘制的点,然后在加载时重新绘制它们。与我的项目完美搭配。
    猜你喜欢
    • 2012-02-16
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2019-01-17
    • 2017-04-22
    • 2011-08-17
    相关资源
    最近更新 更多