Canvas getImageData() For optimal performance. To pull out all data or one at a time?

前端 未结 3 750
长情又很酷
长情又很酷 2021-02-02 04:06

I need to scan through every pixel in a canvas image and do some fiddling with the colors etc. For optimal performance, should I grab all the data in one go and work on it throu

3条回答
  •  [愿得一人]
    2021-02-02 04:50

    Additionally to what GameAlchemist said, if you want to get or set all the colors of a pixel simultaneously, but you don't want to check endianness, you can use a DataView:

    var data = context.getImageData(0, 0, canvas.width, canvas.height);
    var view = new DataView(data.data.buffer);
    
    // Read or set pixel (x,y) as #RRGGBBAA (big endian)
    view.getUint32(4 * (x + y*canvas.width));
    view.setUint32(4 * (x + y*canvas.width), 0xRRGGBBAA);
    
    // Read or set pixel (x,y) as #AABBGGRR (little endian)
    view.getUint32(4 * (x + y*canvas.width), true);
    view.setUint32(4 * (x + y*canvas.width), 0xAABBGGRR, true);
    
    // Save changes
    ctx.putImageData(data, 0, 0);
    

提交回复
热议问题