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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With