Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript throws: "is not a function" when I pass object as argument

Tags:

javascript

This is my simple code:

var x = 0, y = 0;

function start() {
    var canvas = document.getElementById("myCanvas"), ctx = canvas.getContext("2d");

    animate(ctx);
}

function animate(ctx) {
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(x, y, 20, 20);
    ctx.save();
    x++;
    window.requestAnimationFrame(animate);
}

When I run this code a error occurs "ctx.clearRect is not a function" but when I get context from canvas in method animate instead of pass it as argument it's working.

like image 916
dejmien25 Avatar asked Mar 17 '23 06:03

dejmien25


1 Answers

You have to pass the ctx context on the next tick, otherwise the ctx argument is undefined, and undefined has no method clearRect

function animate(ctx) {
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(x, y, 20, 20);
    ctx.save();
    x++;
    window.requestAnimationFrame(function() {
        animate(ctx);
    });
}

FIDDLE

like image 80
adeneo Avatar answered Apr 28 '23 18:04

adeneo