Get a pixel from HTML Canvas?

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

    function GetPixel(context, x, y)
    {
        var p = context.getImageData(x, y, 1, 1).data; 
        var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);  
        return hex;
    }
    
    function rgbToHex(r, g, b) {
        if (r > 255 || g > 255 || b > 255)
            throw "Invalid color component";
        return ((r << 16) | (g << 8) | b).toString(16);
    }
    

提交回复
热议问题