Canvas How to - Move rectangle left by button








Question

We would like to know how to move rectangle left by button.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){<!--from   www .jav  a 2  s. com-->
x =200;
$('#as').click(function()
{    
    var inc=10;
    var c=document.getElementById("canvas");
    //c.style.backgroundColor = "#ff0000";
    ctx = c.getContext("2d");    
    ctx.fillStyle="#ff0000";    
    ctx.fillRect(x+5,0,15,75);
    ctx.fillStyle="#ffffff";    
    ctx.fillRect(x,0,15,75);
    x-=5;
}
);
});//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="250" height="300"
    style="background-color: red;"></canvas>
  <button id="as" type="button">Left</button>
</body>
</body>
</html>

The code above is rendered as follows: