Javascript examples for Canvas:Key
Use arrow key to move circle
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <title>Demo by Roko C.B.</title> <style> canvas { display:block; } </style> </head> <body> <canvas id="canvas" style="background: #000;"></canvas> <script> $(document).ready(function(){ var canvas = $("#canvas")[0]; var context = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var w = canvas.width; var h = canvas.height; var cw;/*from www .j av a 2s .c om*/ var dot; var radius; var d; function init(){ cw=15; radius=25; create_dot(); if(typeof game_loop != "undefined") clearInterval(game_loop); game_loop = setInterval(paint, 40); } init(); function create_dot(){ dot = { x: Math.random()*w, y: Math.random()*h }; } function paint(){ canvas.width = canvas.width; if(d == "right") dot.x=dot.x+10; else if(d == "left") dot.x=dot.x-10; else if(d == "up") dot.y=dot.y-10; else if(d == "down") dot.y=dot.y+10; paint_cell(dot.x,dot.y); } function paint_cell(x, y) { context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); context.fillStyle = 'yellow'; context.fill(); } $(document).keydown(function(e){ var key = e.which; if(key == "37") d = "left"; else if(key == "38") d = "up"; else if(key == "39") d = "right"; else if(key == "40") d = "down"; }); console.log(dot.x); console.log(dot.y); }); </script> </body> </html>