Я думаю, вы неправильно поняли, "как работает анимация на холсте". Это не какая-то анимация CSS. В канве вам нужно собрать все кадры, необходимые для анимации, вы можете найти несколько библиотек, чтобы сделать это проще.
Итак, вам нужно перекрашивать черный блок непрерывно с уменьшением значения x, чтобы заставить его двигаться. Так что ваша логика количества шагов = количество перерисовок может быть неправильной.
В любом случае, перемещая часть черного блока, вы можете добиться этого с помощью этого кода.
const WIDTH = 640;
const HEIGHT = 480;
/* Moving Block */
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var SPEED = 10;
function Block() {
this.width = Math.floor(Math.random() * 100);
this.height = Math.floor(Math.random() * 100);
// Make sure the block doesn't go out of view
this.y = Math.floor(Math.random() * (HEIGHT - this.height));
// Randomize the direction from which to calculate ulY
if (Math.random() > 0.5) {
this.y = HEIGHT - this.y - this.height;
}
// Make sure the block doesn't go out of view
this.x = WIDTH - this.width;
this.distanceToCross = WIDTH - this.width;
this.timeToCross = (this.distanceToCross / SPEED) * 100;
requestAnimationFrame(this.animate.bind(this));
}
Block.prototype.draw = function () {
context.clearRect(0, 0, WIDTH, HEIGHT);
context.fillStyle = "#000000";
context.fillRect(this.x, this.y, this.width, this.height);
};
Block.prototype.animate = function (timestamp) {
if (!this.start) {
this.start = timestamp;
}
this.x = this.distanceToCross * (1 - ((timestamp - this.start) / this.timeToCross));
this.draw();
if (this.x <= 0 - this.width) {
console.log(new Block());
} else {
requestAnimationFrame(this.animate.bind(this));
}
};
console.log(new Block());
https://codepen.io/anon/pen/ZoXdPB