Programming Basics: A website for teaching people how to program
 

Graphics and Animation with HTML5 Canvas and Javascript: Base Code

<!DOCTYPE html>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
  canvas = document.getElementById('canvas');
  c = canvas.getContext('2d');
  c.clear = function() {this.clearRect(0,0,500,500);};
  function wait(fn) {window.setTimeout(fn, 250); }
  function repeat(fn) {
    if (window.requestAnimationFrame) {
      var advance = function() {fn(); requestAnimationFrame(advance);};
      requestAnimationFrame(advance);
    } else window.setInterval(fn, 50);
  }
  var dx = 0, dy = 0, mousex = 0, mousey=0, mouseclicks = 0;
  document.onkeydown = function(e) {
    var key = e.keyCode;
    if (key == 37) dx=-1; 
    else if (key == 38) dy=-1; 
    else if (key == 39) dx=1; 
    else if (key == 40) dy=1; else return true; 
    return false;
  };
  document.onkeyup = function(e) {
    var key = e.keyCode; 
    if (key == 37 || key == 39) dx=0; 
    else if (key == 38 || key == 40) dy=0;
    else return true; 
    return false;
  };
  canvas.onmousemove = function(e) {
    var rect = canvas.getBoundingClientRect(); 
    mousex = e.clientX - rect.left; 
    mousey = e.clientY - rect.top;
  };
  canvas.onmousedown = function(e) {mouseclicks++;};
</script>

Programming Basics

E-mail | About | Privacy Policy