Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a complete, self-contained example. First, use the following HTML:</p> <pre><code>&lt;canvas id="example" width="200" height="60"&gt;&lt;/canvas&gt; &lt;div id="status"&gt;&lt;/div&gt; </code></pre> <p>The relevant JavaScript:</p> <pre><code>// set up some sample squares var example = document.getElementById('example'); var context = example.getContext('2d'); context.fillStyle = "rgb(255,0,0)"; context.fillRect(0, 0, 50, 50); context.fillStyle = "rgb(0,0,255)"; context.fillRect(55, 0, 50, 50); $('#example').mousemove(function(e) { var pos = findPos(this); var x = e.pageX - pos.x; var y = e.pageY - pos.y; var coord = "x=" + x + ", y=" + y; var c = this.getContext('2d'); var p = c.getImageData(x, y, 1, 1).data; var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6); $('#status').html(coord + "&lt;br&gt;" + hex); }); </code></pre> <p>The code above assumes the presence of jQuery and the following utility functions:</p> <pre><code>function findPos(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return { x: curleft, y: curtop }; } return undefined; } function rgbToHex(r, g, b) { if (r &gt; 255 || g &gt; 255 || b &gt; 255) throw "Invalid color component"; return ((r &lt;&lt; 16) | (g &lt;&lt; 8) | b).toString(16); } </code></pre> <p>See it in action on JSFIDDLE:</p> <ul> <li><a href="http://jsfiddle.net/DV9Bw/1/" rel="noreferrer">http://jsfiddle.net/DV9Bw/1/</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload