Search code examples
javascripthtmlcanvas

Canvas in HTML5: Removing Previous Rectangle


I've been messing around with the canvas element in html5, and this is what I've got after a bit of experimenting

function canvasMove(e) {

    var canvas = document.getElementById('game');

    if(canvas.getContext) {
        var draw = canvas.getContext('2d');

        draw.fillStyle = 'rgba(0,0,0,0.5)';
        draw.fillRect('10', '10', '100', '100');    

        var code;

        if (!e) var e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        if(character == '&') { draw.translate(0, -10); }
        if(character == '(') { draw.translate(0, 10); }
        if(character == '%') { draw.translate(-10, 0); }
        if(character == "'") { draw.translate(10, 0); }
    }
}

What it does is moves the rectangle whenever you press the arrow keys [Arrow keys were showing up as &, (, % and ', not sure if this is the same for everyone but it's just an experiment]. Anyway, I can move the rectangle about but it leaves a sort of residue, as in it doesn't delete it's previous form, so what I get is a very basic etch-n'-sketch using a very thick brush.

What I want to do is be able to delete the previous form of the rectangle so that only the new translated version is left.

On top of that I'd like to know how to make it move say, horizontally, by pressing maybe left and up simultaneously. I am aware my code probably isn't very versatile, but any help us much appreciated.

Thanks :)


Solution

  • I made an example for you. Your HTML has to call my init() function. I used:

    <body onLoad="init()">
    

    Let me know if you have any problems with it

    var canvas;
    var draw;
    
    var WIDTH;
    var HEIGHT;
    
    var x = 10;
    var y = 10;
    
    // in my html I have <body onLoad="init()">
    function init() {
        canvas = document.getElementById('game');
        HEIGHT = canvas.height;
        WIDTH = canvas.width;
        draw = canvas.getContext('2d');
    
        // every 30 milliseconds we redraw EVERYTHING.
        setInterval(redraw, 30);
    
        // canvas.keydown = canvasMove;
    
        document.onkeydown = canvasMove; 
    }
    
    //wipes the canvas context
    function clear(c) {
        c.clearRect(0, 0, WIDTH, HEIGHT);
    }
    
    //clears the canvas and draws the rectangle at the appropriate location
    function redraw() {
        clear(draw);
        draw.fillStyle = 'rgba(0,0,0,0.5)';
        draw.fillRect(x, y, '100', '100');   
    }
    
    function canvasMove(e) {
      if(e.keyCode == '38') { y -= 1; }
      if(e.keyCode == '40') { y += 1; }
      if(e.keyCode == '37') { x -= 1; }
      if(e.keyCode == "39") { x += 1; }
    }