Mitch Wardle
Mitch Wardle

Reputation: 35

How do I redraw a rectangle?

I am using javascript and I've drawn a rectangle with the width set to a variable. When I increase or decrease the variable how can I get the rectangle the redraw instead of drawing a new rectangle with the width of the updated variables? below is an example, when I press the left arrow it will decrease the variable. I think the problem could be that I've put the fillRect code in the Render function so it redraws every time the function is called. That could be what is wrong but I don't know how to correct it. Below is an example code.

$(function(){
//START OF VARIABLES///////////////////////////////////

//INITIALISE CANVAS
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = (32*12);
canvas.height = (32*12);

//HANDLES KEYBOARD INPUT
var keysDown = {};

addEventListener("keydown", function (e) {
   keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
   delete keysDown[e.keyCode];
}, false);

var leftarrow = 37;
var uparrow = 38;
var rightarrow = 39;
var downarrow = 40;

//PLAYER VARIABLES
var health = 100

//END OF VARIABLES///////////////////////////////////// 

function Initalise(){
    Main();
}

function Update(modifier) {

    if(leftarrow in keysDown){
        health -= 1;   
    }
}

function Render(){
    ctx.fillStyle = "red";
    ctx.fillRect(80, 10, health, 10);
}

function Main() {
    var now = Date.now();
    var delta = now - then;

    Update(delta / 1000);
    Render();

    then = now;

    requestAnimationFrame(Main);
}

var then = Date.now();
Initalise();
});

Upvotes: 0

Views: 460

Answers (1)

Casey Rule
Casey Rule

Reputation: 2085

You'll need to add two things to make this work as expected. First, you need to call Render from the Update function. Second, you'll need to clear the canvas before redrawing the rectangle.

function Update(modifier) {
    if(leftarrow in keysDown){
        health -= 1;   
    }
    Render();
}

function Render(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "red";
    ctx.fillRect(80, 10, health, 10);
}

Upvotes: 2

Related Questions