Draw image from pixel array on canvas with putImageData

前端 未结 2 1045
不思量自难忘°
不思量自难忘° 2021-02-14 12:50

I am working on a project that can encrypt an image and redraw the decrypted image on canvas. As I am still pretty new to coding and programming, I am currently having issues re

2条回答
  •  野性不改
    2021-02-14 13:40

    Using Uint8 you can this much quicker:

    var canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d"),
        img = [27,32,26,28, ... ];
    
    // Get a pointer to the current location in the image.
    var palette = ctx.getImageData(0,0,160,120); //x,y,w,h
    // Wrap your array as a Uint8ClampedArray
    palette.data.set(new Uint8ClampedArray(img)); // assuming values 0..255, RGBA, pre-mult.
    // Repost the data.
    ctx.putImageData(palette,0,0);
    

    No need to go byte-by-byte unless you need to modify the values first.

提交回复
热议问题