Canvas How to - Move image with keyboard








Question

We would like to know how to move image with keyboard.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w w  w .j av  a2  s  .  c  o m-->
    var x=120;
    var y=120;
    var key,pos=0;
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var img=new Image();
    img.onload=function()
    {
      ctx.drawImage(img,x,y);
    }
    img.src="http://www.java2s.com/style/download.png";
    document.onkeydown=function(e)
    {
      pos++;
      key=window.event?e.keyCode:e.which;
    }
    document.onkeyup=function(e){pos--}
    setInterval(function()
    {
      if(pos==0)return;
      if(key==37)x-=2;
      if(key==38)y-=2;
      if(key==39)x+=2;
      if(key==40)y+=2;
        canvas.width=canvas.width;
      ctx.drawImage(img,x,y);
    },5);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="300" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: