Get a pixel from HTML Canvas?

后端 未结 10 2105
情深已故
情深已故 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:21

    If you want to extract a particular color of pixel by passing the coordinates of pixel into the function, this will come in handy:

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    function detectColor(x, y){
      data=ctx.getImageData(x, y, 1, 1).data;
      col={
        r:data[0],
        g:data[1],
        b:data[2]
      };
      return col;
    }
    

    x, y is the coordinate you want to filter out color.

    var color = detectColor(x, y)
    

    The color is the object, you will get the RGB value by color.r, color.g, color.b.

提交回复
热议问题