Carl Miller
Carl Miller

Reputation: 113

Tracking mouse hover on html5 canvas

does anyone know if pixel color tracking on mouse hover can be done with html5 canvas to get the same results in the video below?

player tracking hover example

Upvotes: 0

Views: 213

Answers (1)

Joseph Gast
Joseph Gast

Reputation: 71

This seems to be a duplicate of How to get a pixel's x,y coordinate color from an image?

The top answer on that article provides a good explanation, as well as links this fiddle with some code that does exactly what you are looking for. I have also included the JS portion below which has a dependency on jquery

$(function() {

    $('img').mousemove(function(e) {

        if(!this.canvas) {
            this.canvas = $('<canvas />')[0];
            this.canvas.width = this.width;
            this.canvas.height = this.height;
            this.canvas.getContext('2d').drawImage(this, 0, 0, this.width, this.height);
        }

        var pixelData = this.canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

        $('#output').html('R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3]); 
    });
});

Upvotes: 1

Related Questions