Serialize canvas content to ArrayBuffer and deserialize again

后端 未结 3 1722
囚心锁ツ
囚心锁ツ 2021-01-02 02:27

I have two canvas, and I want to pass the content of canvas1, serialize it to an ArrayBuffer, and then load it in canvas2. In the future I will send the canvas1 content to t

3条回答
  •  孤城傲影
    2021-01-02 02:51

    The ImageData you get from getImageData() is already using an ArrayBuffer (used by the Uint8ClampedArray view). Just grab it and send it:

    var imageData = context.getImageData(x, y, w, h);
    var buffer = imageData.data.buffer;  // ArrayBuffer
    

    To set it again:

    var imageData = context.createImageData(w, h);
    imageData.data.set(incomingBuffer);
    

    You probably want to consider some form of byte encoding though (such as f.ex base-64) as any byte value above 127 (ASCII) is subject to character encoding used on a system. Or make sure all steps on the trip uses the same (f.ex. UTF8).

提交回复
热议问题