Get a pixel from HTML Canvas?

后端 未结 10 2158
情深已故
情深已故 2020-11-22 12:41

Is it possible to query a HTML Canvas object to get the color at a specific location?

10条回答
  •  被撕碎了的回忆
    2020-11-22 13:23

    Yes sure, provided you have its context. (See how to get canvas context here.)

    var imgData = context.getImageData(0,0,canvas.width,canvas.height);
    // { data: [r,g,b,a,r,g,b,a,r,g,..], ... }
    
    function getPixel(imgData, index) {
      var i = index*4, d = imgData.data;
      return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
    }
    
    // AND/OR
    
    function getPixelXY(imgData, x, y) {
      return getPixel(imgData, y*imgData.width+x);
    }
    



    PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray

    var
      idt = imgData, // See previous code snippet
      a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
      b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]
    
    a[0] = 255 // Does nothing
    getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
    
    b[0] = 255 // Mutates the original imgData.data
    getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]
    
    // Or use it in the function
    function getPixel(imgData, index) {
      var i = index*4, d = imgData.data;
      return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
    }
    

    You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.

提交回复
热议问题