Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Responding to canvas click events</strong></p> <p><strong>Oops</strong>, it looks like your question was cut off! On your next question, be sure not to hit the “Enter” key—instead of starting a new line in your question, you will immediately post your partially written question (don’t worry…we’ve all done it). </p> <p>And Nick, “Welcome to stackoverflow” – it really is full of answers!</p> <p>Norguard is right about the canvas not being able to keep track of which image you clicked on. Think of canvas as an artist's easel and you are painting images on that easel. Yes, the easel contains the images, but the easel has no way of knowing where you drew any image.</p> <p>To keep your life simple while you’re learning, try starting with having just 1 image per canvas (yes, you can have as many canvas elements as you have images). </p> <p>If you want to start with 1 image per canvas, here is code and a Fiddle: <a href="http://jsfiddle.net/m1erickson/KGKYg/" rel="nofollow">http://jsfiddle.net/m1erickson/KGKYg/</a></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /&gt; &lt;!-- reset css --&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery.min.js"&gt;&lt;/script&gt; &lt;style&gt; body{ background-color: ivory; } canvas{border:1px solid red;} &lt;/style&gt; &lt;script&gt; $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var img=new Image(); img.onload=function(){ canvas.width=img.width; canvas.height=img.height; ctx.drawImage(img,0,0); } img.src="http://dl.dropbox.com/u/139992952/coffee.png"; canvas.addEventListener("click", function (e) { alert("use your linke totake me away...!"); }); }); // end $(function(){}); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="canvas" width=300 height=300&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>[Edit: Responding to keyboard events]</strong></p> <p>Here's how you can listen for user keypresses and respond to them:</p> <pre><code>// listen for keyboard events window.addEventListener('keydown',keyIsDown,true); // process the keystrokes function keyIsDown(event){ switch (event.keyCode) { case 38: // "UP" was pressed, do UP stuff break; case 40: // "DOWN" was pressed, do DOWN stuff break; } } </code></pre>
 

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