javascript - canvas how to move rect using arrows -
i started learning canvas today, started off creating simple rectangle, need make rectangle move using arrow keys, moveto function doesn't seem anything, how can achieve this. code far
<html> <head> <title></title> </head> <body> <canvas id="mycanvas" width="600" height="250" style="border:1px solid black;"> </canvas> <script type="text/javascript"> var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d"); context.fillstyle = "green"; var x = 50,y=5,w=100,h=100; context.fillrect(x,y,w,h); document.onkeydown = function move() { switch(window.event.keycode) { case 37: { //left context.moveto(x++,y); break; } case 38: { console.log('up'); break; } case 39: { console.log('right'); break; } case 40: { console.log('down'); break; } } } </script> </body> </html>
you can't move rectangles around canvas after you've drawn them fillrect.
the canvas image, rectangle becomes unmovable shape painted on canvas.
to "move" shapes, must clear canvas , redraw shape in new position.
btw, context.moveto path command tells context move drawing pen specified location. not move existing shape on canvas.
for example, in keyhandler when responding left-arrow key:
change x coordinate leftward: x--;
clear canvas: context.clearrect(0,0,canvas.width,canvas.height);
redraw rectangle @ new position: context.fillrect(x,y,w,h);
Comments
Post a Comment