简体   繁体   中英

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:)

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; }
}

To answer the first question here is a function to clear a canvas. A is a reference to canvas element though you could edit what parameters it takes. You would need to call this every time before you draw a new rectangle.

function clear(a){
    a.getContext('2d').clearRect(0,0,a.width,a.height);
}

I think in the second question you meant move at an angle. As far as I know that would be a little difficult because you would have record the key press and then set a timeout to see if another one was pressed within some amount of time. Then create a function to move both of those directions or just one if no other arrow keys were pressed. Right now your function would kind of work if both key were pressed, but the rectangle would jerk left and then up.

If you wanted to do this without redrawing the canvas, you can do a save on the context, set your transformation and then clear the rectangle off your screen while still remembering where that rectangle would have been drawn. Then call the translate to move the rectangle to its new position.

<!DOCTYPE html>
<body>
<button onClick="canvasMove('down');">Down</button>
<canvas id="game" style="padding-top:200px;background-color:white;" 
       height="300" width="300" />
</body>
<script>
const canvas = document.getElementById('game');
const draw = canvas.getContext('2d');
draw.fillStyle = 'rgba(0,0,0,0.5)';
draw.fillRect('10', '10', '100', '100');

function canvasMove(direction) {
    // save the current state of the canvas and then clear the canvas,
    // which removes any object on your canvas
    draw.save();        
    draw.setTransform(1, 0, 0, 1, 0, 0);
    draw.clearRect(0, 0, canvas.height, canvas.width);  
    // reverts canvas back to its saved state
    draw.restore();

    if(direction === 'down') {       
       draw.translate(0, 10);       
       draw.fillStyle = 'rgba(0,0,0,0.5)';
       draw.fillRect('10', '10', '100', '100');
    }      
}
</script>

To get the same effect, you don't even need to do the save and restore. Context.globalCompositeOperation = "copy" will only draw the new object.

function canvasMove(direction) {    
    draw.globalCompositeOperation = "copy";

    if(direction === 'down') {       
       draw.translate(0, 10);       
       draw.fillStyle = 'rgba(0,0,0,0.5)';
       draw.fillRect('10', '10', '100', '100');
    }      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM