【问题标题】:Add local storage to save canvas drawing添加本地存储以保存画布绘图
【发布时间】:2018-06-13 10:20:04
【问题描述】:

我不知道如何添加本地存储来保存在画布上制作的绘图,因此当重新加载页面时,现有绘图会通过本地存储加载到画布上。我没有必须的经验,如果有人可以使用本地存储添加编辑我的代码,我将不胜感激。非常感谢!

这是我的 JS:

var canvas, ctx,
    brush = {
        x: 0,
        y: 0,
        color: '#000000',
        size: 10,
        down: false,
    },
    strokes = [],
    currentStroke = null;

function redraw () {
    ctx.clearRect(0, 0, canvas.width(), canvas.height());
    ctx.lineCap = 'round';
    for (var i = 0; i < strokes.length; i++) {
        var s =strokes[i];
        ctx.strokeStyle = s.color;
        ctx.lineWidth = s.size;
        ctx.beginPath();
        ctx.moveTo(s.points[0].x, s.points[0].y);
        for (var j = 0; j < s.points.length; j++){
            var p = s.points[j];
            ctx.lineTo(p.x, p.y);
        }
        ctx.stroke();
    }

}
function init () {
    canvas = $('#draw');
    canvas.attr({
        width: window.innerWidth,
        height: window.innerHeight,
    });
    ctx = canvas[0].getContext('2d');


    function mouseEvent (e){
                brush.x = e.pageX;
        brush.y = e.pageY;

        currentStroke.points.push({
            x: brush.x,
            y: brush.y,

        });



        redraw();
    }
    canvas.mousedown(function (e){
        brush.down = true;

        currentStroke = {
            color: brush.color,
            size: brush.size,
            points: [],
        };
        strokes.push(currentStroke);

        mouseEvent(e);
    }) .mouseup(function (e) {
        brush.down = false;

        mouseEvent(e);

        currentStroke = null;
    }) .mousemove(function (e) {
        if (brush.down)
            mouseEvent(e);
    });

    $('#save-btn').click(function () {
        window.open(canvas[0].toDataURL());
    });
    $('#undo-btn').click(function (){
        strokes.pop();
        redraw();
    });
    $('#clear-btn').click(function (){
        strokes = [];
        redraw();
    });

    $('#color-picker').on('input', function () {
        brush.color = this.value;
    });
    $('#brush-size').on('input', function () {
        brush.size = this.value;
    });
    }
$(init);

【问题讨论】:

  • 你坚持什么? Localstorage 存储字符串,以便对画布内容进行序列化/反序列化。
  • 我不知道如何实际实现本地存储
  • 你不需要实现localstorage,你使用API​​。类似localStorage.setItem('image', canvas.toDataURL());
  • 如何在我的代码中实现这一点? (我几乎没有任何编码知识)

标签: javascript canvas local-storage


【解决方案1】:

Canvas.js 会将画布作为图像保存到 localStorage,这对您的情况没有帮助,因为您将鼠标事件存储在数组中。

如果您正在寻找一种解决方案,可以让您继续在画布上绘图并恢复旧(已保存)元素,您需要将画布元素(在您的情况下为 strokes 数组)存储在localStorage 和恢复,重绘画布

这是一个演示:

JS FIDDLE DEMO

  1. 在画布上绘制任何东西。
  2. 点击底部的“保存到本地存储”按钮。
  3. 刷新页面。

要清除 localStorage,请清除浏览器缓存。

相关代码更改:

  1. 在 HTML 中添加了一个按钮以保存到本地存储

    <button id="save-to-local-storage">
       Save to local storage
    </button>
    
  2. 点击上面的按钮将strokes数组保存到localStorage。

    $('#save-to-local-storage').click(function () {
      localStorage.setItem('canvas_strokes', JSON.stringify(strokes)); 
    });
    
  3. 页面刷新时,检查localStorage是否设置了项目,如果是,则重绘画布:

    // check if localstorage has an array of strokes saved 
    if(localStorage.getItem('canvas_strokes')) { 
       strokes = JSON.parse(localStorage.getItem('canvas_strokes'));
       redraw();
    }
    

如果您有任何问题,请告诉我。希望这可以帮助。 :)

【讨论】:

  • Canvas.js 实现了一个新功能,我对完整的代码做了一些修改。谢谢!
  • 太棒了。很高兴我能做出贡献! :)
【解决方案2】:

使用Canvas.js 助手,您可以简单地做到:

const canvas = new Canvas( 'my-canvas' );
canvas.saveToStorage( 'balls' );

在哪里

  • my-canvas画布 ID
  • balls 是将其保存为的

稍后恢复画布状态:

const canvas = new Canvas( 'my-canvas' );
canvas.restoreFromStorage( 'balls' );

加载Canvas.js:

<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Canvas.js">

编辑

看完下面的帖子(谢谢@Shashank),我用完整的代码做了一个jsfiddle来实现连续绘图。它会在 mouseup 上自动保存最后一个笔划并在刷新时加载它。看看吧!

它使用Canvas.jsPointer.js

https://jsfiddle.net/wk5ttqa2/

编辑 2

只是为了好玩......这真的很简单:

https://jsfiddle.net/GustavGenberg/1929f15t/1/

请注意,快速移动时它不会绘制完整的线条(取决于帧率)...

【讨论】:

  • 也许你想在 Canvas.js 中有 two separate 函数,即saveCanvasToStorage - 它将它保存为图像 - 就像它一样现在(我查找了库函数)和saveCanvasElementsToStorage - 这会将array 保存到localStorage。如果您认为我可以分叉并向您的存储库添加提交,请告诉我。
  • 我们在这里谈论什么元素?笔画“元素”?
  • 你查看我的answer了吗?在这种情况下,元素被存储在一个名为strokes 的数组中。试试fiddle 链接。
  • 好的,您应该能够存储什么以及如何存储?我想知道如果您可以加载handyObject并将其保存到存储中,这是否是一个好的解决方案?随意 fork n commit :)
  • 您是否尝试绘制任何图像并单击底部的“保存到本地存储”按钮?保存为字符串作为 JSON 解析它来获取?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 2014-03-22
  • 2016-10-24
  • 1970-01-01
  • 2014-09-27
相关资源
最近更新 更多