HTML5画布-保存和恢复拖放画布状态

HTML5 Canvas - Saving and Restoring drag and drop canvas states

本文关键字:布状态 状态 拖放 画布 保存 恢复 HTML5      更新时间:2023-09-28

使用这个JS Fiddle我能够动态创建画布,并在所有不同的画布之间拖放图像。

var next = 4
    function addCanvas() {
        // create a new canvas element
        var newCanvas = document.createElement("canvas");
        newCanvas.id = "addedcanvases" + next; //added this to give each new canvas a unique id
        next++;
        newCanvas.width = canvasWidth;
        newCanvas.height = canvasHeight;
        // add a context for the new canvas to the contexts[] array
        contexts.push(newCanvas.getContext("2d"));
        // link the new canvas to its context in the contexts[] array
        newCanvas.contextIndex = contexts.length;
        // wire up the click handler
        newCanvas.onclick = function (e) {
            handleClick(e, this.contextIndex);
        };
        // wire up the mousemove handler
        newCanvas.onmousemove = function (e) {
            handleMousemove(e, this.contextIndex);
        };
        // add the new canvas to the page
        document.body.appendChild(newCanvas);
    }

问题:

$("#saveCanvasStates").click(function () {
     // save canvases and images on them to a database
});

在画布之间进行拖放操作结束时,用户需要能够按下"保存"按钮(此处显示JSFIDDLE),该按钮将把所有画布的当前状态保存到数据库,即:

  • 将所有画布保存到数据库
  • 保存哪些图像在哪些画布上

这样,用户就可以在以后的时间回来,从他们停止的地方继续-拖放功能仍然有效。

做这件事的最佳方式是什么?

保存/恢复用户工作所需的所有信息都在states[]数组中,该数组包含定义所有拖放项状态的javascript对象。

事实上。。。

有很多关于序列化、传输、保存、检索和反序列化javascript对象的信息;)

对于序列化javascript对象,请使用JSON.stringify,它可以将对象数组序列化为单个JSON字符串(JSON代表JavaScriptObjectNotation)。这个字符串可以很容易地传输到您的服务器,以便发布到您的数据库。

为了返回您的状态信息,您可以要求服务器返回相同的JSON字符串。您可以使用JSON.parse将JSON字符串转换回对象数组。

要传输和接收JSON数据字符串,可以使用jQueries $.ajax方法。Ajax可以用来向服务器发送信息,这被称为Ajax POST。Ajax可以用于从服务器请求信息,这被称为Ajax GET。

当您的服务器收到POST请求时,它将接受您提供的JSON字符串并将其保存在数据库中。

当您的服务器收到GET请求时,它将查询数据库以检索保存的JSON字符串,并将其发送回用户。

设置服务器和数据库超出了stackoverflow问题的范围,但这里有一系列关于如何将jQuery、JSON、Ajax、Php和MySQL数据库一起用于保存和恢复状态的教程:

www.youtube.com/watch?v=Yz0RF__mFDU

下面是一个用于序列化和POST状态信息的客户端代码的快速示例:

// Serialize the states array
var JsonStringForTransport = JSON.stringify({stateForUserNumber7: states});
// POST the JSON to your server
var thePost = $.ajax({
    url: 'saveToServer.php',
    type: 'POST',
    dataType: 'json',
    data: JsonStringForTransport,
    contentType: 'application/json; charset=utf-8'
});
thePost.always(function(result){  
    // use this during testing to be sure something's happening
});
thePost.fail(function(result){  
    // handle failure
});
thePost.done(function(result){  
    // handle success
});

祝你的项目好运!:)