Canvas How to - Get color from x,y








Question

We would like to know how to get color from x,y.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- www. j av  a  2s . co m-->
    var cv  = document.getElementById('cv'),ctx = cv.getContext('2d');
    for(var i = 0; i <= 255; i++) {
        ctx.beginPath();
        var color = 'rgb(100, ' + i + ', ' + i + ')';
        ctx.fillStyle = color;
        ctx.fillRect(i * 2, 0, 2, 50);
    }
    cv.onclick = function(e) {
        var x = e.offsetX,
            y = e.offsetY,
            p = ctx.getImageData(x, y, 1, 1),
            x = p.data;
        alert('Color: rgb(' + x[0] + ', ' + x[1] + ', ' + x[2] + ')');
    };
}//]]>  
</script>
</head>
<body>
  <canvas width="512" height="50" id="cv"></canvas>
</body>
</html>

The code above is rendered as follows: