Reading the RGB value of a canvas pixel

后端 未结 2 735
陌清茗
陌清茗 2021-01-05 16:50

I have put an image in canvas and I want to get the RGB value of the pixels of that image when the user moves the mouse over the image. Here is the code which I have writte

2条回答
  •  难免孤独
    2021-01-05 17:10

    What you're looking for here is the getImageData() call.

    So, your solution would look something like this:

    function getColor(canvas, x, y) {    
        var context = canvas.getContext("2d");
        var pixel = context.getImageData(x, y, 1, 1);
    
        // Red = rgb[0], green = rgb[1], blue = rgb[2]
        // All colors are within range [0, 255]
        var rgb = pixel.data;
    
        return rgb;
    }
    
    function canvasMouseMove(e) {
        var x = e.layerX, y = e.layerY;
        var rgb = getColor(canvas, x, y);
        var rgb_string = "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";
    
        document.body.style.backgroundColor = rgb_string;
    }
    
    canvas.onmousemove = canvasMouseMove;
    

    As @bebraw pointed out, you may need to handle the mouse location differently depending on the browser being used. For that, you might consider using jQuery or another JS library for simplicity.

提交回复
热议问题