(think of a flip book!)
context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
To repeatedly draw and clear out images, we can use a built-in function called setInterval - it takes two parameters:
// will repeatedly call animate every 10ms
setInterval(animate, 10);
In order to keep track of how our drawing moves, will need to use a few variables:
document.addEventListener('DOMContentLoaded', main);
var sketch;
var context;
var rectangle = {'x':0, 'y':100};
var dx = 1;
var fps = 10;
function main() {
sketch = document.getElementById('sketch');
context = sketch.getContext("2d");
setInterval(animate, fps);
}
function animate() {
context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
context.fillRect(rectangle.x, rectangle.y, 120, 40);
rectangle.x = rectangle.x + dx;
}
We can use sketch.offsetWidth and sketch.offsetHeight to determine horizontal and vertical boundaries.
If the position of our drawing reaches these boundaries, change its velocity by multiplying by -1… and setting the position appropiately…
(Click the link above. Arrow right when ready to proceed...)
document.addEventListener('DOMContentLoaded', main);
var sketch;
var context;
var rectangle = {'x':0, 'y':100, 'w':120, 'h':40};
var dx = 3;
var fps = 10;
function main() {
sketch = document.getElementById('sketch');
context = sketch.getContext("2d");
setInterval(animate, fps);
}
function animate() {
context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
context.fillRect(rectangle.x, rectangle.y, 120, 40);
rectangle.x = rectangle.x + dx;
if (rectangle.x > sketch.offsetWidth - rectangle.w - dx) {
dx = dx * -1;
rectangle.x = offsetWidth;
} else if (rectangle.x < 0 + dx) {
dx = dx * -1;
rectangle.x = 0;
}
}
(Click the link above...)