Javascript examples for Canvas:Animation
HTML 5 canvas keydown event animation
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.js"></script> <script type="text/javascript"> $(window).load(function(){/* www . jav a 2 s.c om*/ var main = function (){ canvas = document.getElementById("canvas"); window.addEventListener("keydown", doKeyDown, true); ctx = canvas.getContext("2d"); ctx.fillStyle = "rgba(0, 0, 255, 1)" ctx.fillRect(20, 20, 20, 15); x = 30; y = 30; }; $(document).ready(main); function doKeyDown(key) { if (key.keyCode == 87) { //w clearCanvas(); y = y - 10; ctx.fillStyle = "rgba(0, 0, 255, 1)" ctx.fillRect(x, y, 20, 15) } if (key.keyCode == 83) { //s clearCanvas(); y = y + 10; ctx.fillStyle = "rgba(0, 0, 255, 1)" ctx.fillRect(x, y, 20, 15) } if (key.keyCode == 65) { //a clearCanvas(); y = x - 10; ctx.fillStyle = "rgba(0, 0, 255, 1)" ctx.fillRect(x, y, 20, 15) } if (key.keyCode == 68) { //d clearCanvas(); y = x + 10; ctx.fillStyle = "rgba(0, 0, 255, 1)" ctx.fillRect(x, y, 20, 15) } } function clearCanvas() { canvas.width = canvas.width; } }); </script> </head> <body> <canvas id="canvas" width="400" height="500"></canvas> </body> </html>