Reading the RGB value of a canvas pixel

后端 未结 2 723
陌清茗
陌清茗 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.

    0 讨论(0)
  • 2021-01-05 17:16

    Try something along this:

    var color = document.getElementById("color");
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    
    var imageObj = new Image();
    imageObj.onload = function(){
        context.drawImage(imageObj, destX, destY);
    };
    imageObj.src = "zain.jpg";
    
    canvas.onmousemove = function(e) {
        // not so sure about these... might need to offset them or so
        var x = e.x;
        var y = e.y;
    
        // set color now
        var canvasColor = context.getImageData(x, y, 1, 1).data; // rgba e [0,255]
        var r = canvasColor[0];
        var g = canvasColor[1];
        var b = canvasColor[2];
    
        color.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
    }
    

    Note that the snippet expects you have a div with id "color" somewhere. It sets the pixel color there.

    0 讨论(0)
提交回复
热议问题