Javascript Canvas Serialization/Deserialization?

后端 未结 2 821
暖寄归人
暖寄归人 2020-12-14 11:01

Can you serialize/deserialize a canvas object in javascript?

相关标签:
2条回答
  • 2020-12-14 11:39

    You can get direct pixel access with canvas.getImageData() and .putImageData(). You can also serialize images to a data URL with canvas.toDataURL() for posting to a server.

    This only works in newer browsers.

    0 讨论(0)
  • 2020-12-14 11:44

    Besides the getImageData method, you can use canvas.toDataURL() to get an data-URL-encoded PNG. If you need to serialize to a string, it would save having to convert the raw data to a string manually. You could deserialize by creating an image and setting the src to the data URL, then drawing it to a canvas.

    [Edited to account for asynchronous loading (suggested by olliej).]

    function serialize(canvas) {
        return canvas.toDataURL();
    }
    
    function deserialize(data, canvas) {
        var img = new Image();
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext("2d").drawImage(img, 0, 0);
        };
    
        img.src = data;
    }
    

    If I remember correctly, some older versions of Safari, and maybe Opera didn't support toDataURL, but the more recent versions do.

    0 讨论(0)
提交回复
热议问题