Get color at mouse position in a canvas - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Get color at mouse position in a 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-latest.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w ww  .  j  av  a  2s .c om
      var actualColor = "ffffff";
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.canvas.width = 150;
    context.canvas.height = 200;
function draw() {
    context.beginPath(); context.rect(0,0,canvas.width,canvas.height/2); context.fillStyle="red"; context.fill(); context.closePath();
    context.beginPath(); context.rect(0,canvas.height/2,canvas.width,canvas.height/2); context.fillStyle="blue"; context.fill(); context.closePath();
  }
draw()
    window.addEventListener('load', function(){
        resize();
    });
    window.addEventListener('resize', function(){
        resize();
    });
    function resize() {
        var ratio = canvas.width / canvas.height;
        var canvas_height = window.innerHeight;
        canvas_height -= 130; // remove later
        var canvas_width = canvas_height * ratio;
        if (canvas_width > window.innerWidth) {
            canvas_width = window.innerWidth;
            canvas_height = canvas_width / ratio;
        }
        canvas.style.width = canvas_width + 'px';
        canvas.style.height = canvas_height + 'px';
        canvas.width = canvas_width
        canvas.height = canvas_height
        draw()
    }
    $('#canvas').mousemove(function (e) {
        var pos = {
          x:canvas.offsetLeft,
          y:canvas.offsetTop
        }
        var x = e.pageX - pos.x;
        var y = e.pageY - pos.y;
        var c = canvas.getContext('2d');
        var p = c.getImageData(x, y, 1, 1).data;
        actualColor = ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
        $('#colorOutput').css("background-color", "#" + actualColor);
        $('#status').html(actualColor);
    });
    function rgbToHex(r, g, b) {
        return componentToHex(r) + componentToHex(g) + componentToHex(b);
    }
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas"></canvas> 
      <div id="colorOutput" style="width:100px;height:100px;"></div> 
      <div id="status">
          000000
      </div>  
   </body>
</html>

Related Tutorials