get color from Canvas - Javascript Canvas

Javascript examples for Canvas:Example

Description

get color from Canvas

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {/*from www . j  ava2  s  . c  o m*/
   border:1px solid red;
}
#results {
   width:30px;
   height:30px;
   border:1px solid blue;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var eyedropperIsActive = false;
drawTestColors(20, 20, "red");
drawTestColors(100, 20, "green");
drawTestColors(180, 20, "blue");
function drawTestColors(x, y, color) {
    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.rect(x, y, 50, 50);
    ctx.fill();
}
function getPixelColor(x, y) {
    var pxData = ctx.getImageData(x, y, 1, 1);
    return ("rgb(" + pxData.data[0] + "," + pxData.data[1] + "," + pxData.data[2] + ")");
}
function handleMouseMove(e) {
    if (!eyedropperIsActive) {
        return;
    }
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    var eyedropColor = getPixelColor(mouseX, mouseY);
    $("#results").css("backgroundColor", getPixelColor(mouseX, mouseY));
}
$("#canvas").click(function (e) {
    eyedropperIsActive = false;
});
$("#canvas").mousemove(function (e) {
    handleMouseMove(e);
});
$("#startDropper").click(function (e) {
    eyedropperIsActive = true;
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="300" height="300"></canvas> 
      <br> 
      <button id="startDropper">Activate Eyedropper</button> 
      <div id="results" width="30" height="30">
         &nbsp;
      </div>  
   </body>
</html>

Related Tutorials