0

i'm still learning how to do stuffs in a canvas like this one. Rendering a rectangle object in a y coordinates.

function initCanvas(){
var ctx = document.getElementById('canvas').getContext('2d');
var cW = ctx.canvas.width, cH = ctx.canvas.height;
var y = 0, x = 0;

function rectObj(){
    this.x = 0, this.y = 0;
    this.render = function(ctx, lx, ly, lw, lh, clr){
        ctx.fillStyle = clr;
        ctx.fillRect(lx, ly, lw, lh);
    }
}

var a = rectObj();

function animate(){
    ctx.clearRect(0,0, cW, cH);
    a.render(ctx, 0, a.y, 50, 50, "blue");
    a.y++;
}
var animateInterval = setInterval(animate, 30);

}window.addEventListener('load', function(event){ initCanvas(); });

1 Answer 1

1

You should call the function with new operator:

var a = new rectObj();
Sign up to request clarification or add additional context in comments.

1 Comment

I tried rendering an oop image. But it cannot be rendered though I used the same format of code.. function landObj(){ var land = new Image(); land.src = "land.png"; this.x = 0, this.y = 0, this.w = 0, this.h = 0; this.render = function(ctx, lx, ly, lw, lh){ ctx.drawImage(land, x, y, w, h); } } var land1 = new landObj(); function animate() { ctx.clearRect(0,0, cW, cH); land1.render(ctx, 0, a.y, 50, 50); land1.y++; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.