Javascript examples for Canvas:Rectangle
adding a margin to a fillRect
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <style id="compiled-css" type="text/css"> canvas {/*from w w w .j a v a 2s . c om*/ border: 1px solid black; } </style> <script type="text/javascript"> $(window).load(function(){ var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); var mySnake = [[0, 0], [1,0], [2,0], [3,0]]; function drawSnake(context, snake) { ctx.clearRect(0, 0, 600, 600); var length = snake.length; for (var i = 0; i < length; i++) { context.fillStyle = 'teal'; var position = snake[i]; context.fillRect(position[0]*10, position[1]*10, 9, 9); } } function moveSnake(snake, direction) { snake.shift(); var lastLoc = snake[snake.length - 1]; var lastX = lastLoc[0]; var lastY = lastLoc[1]; switch (direction) { case 'up': snake.push([lastX, lastY-1]); break; case 'down': snake.push([lastX, lastY+1]); break; case 'left': snake.push([lastX-1, lastY]); break; case 'right': snake.push([lastX+1, lastY]); break; } drawSnake(ctx, mySnake); } can.addEventListener('keydown', function(e){ var key = e.which || e.keyCode; console.log(key); var keyname = 'abc'; switch (e.which) { case 38: keyname = 'up'; break; case 40: keyname = 'down'; break; case 37: keyname = 'left'; break; case 39: keyname = 'right'; break; } moveSnake(mySnake, keyname); e.preventDefault(); return false; }, false); drawSnake(ctx, mySnake); }); </script> </head> <body> <canvas id="canvas1" width="600" height="600" tabindex="0"></canvas> </body> </html>