【发布时间】:2017-06-24 03:37:00
【问题描述】:
我想在画布上为矩形设置动画。它在技术上是有效的,但画布在每一帧之前都没有清理干净,并且在地面上留下了一个标记(有点像蜗牛)。我已经进行了研究,一切似乎都指向使用ctx.beginPath() 作为我的问题的解决方案,但是当我尝试在这里使用它时,它不起作用。我做错了什么?
这是原始的 javascript:
// create a canvas element
var canvas = document.createElement("canvas");
// attach element to DOM
document.getElementsByTagName("body")[0].appendChild(canvas);
// get the canvas context (this is the part we draw to)
var ctx = canvas.getContext("2d");
var bug = new Bug(0,0);
function setup() {
// setup the canvas size to match the window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// set the 0,0 point to the middle of the canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
}
function draw() { //Do the drawing
ctx.beginPath();
bug.update();
bug.draw();
window.requestAnimationFrame(function(){draw()});
}
// start enterFrame loop
window.requestAnimationFrame(draw);
// force running setup
setup();
// re-setup canvas when the size of the window changes
window.addEventListener("resize", setup);
// sin(pi) == 0
// cos(pi) == -1
// sin(2pi) == 0
// cos(2pi) == 1
// degrees to radians: {{ deg * (pi/180) = rad }}
function randomRange(max, min) {
return Math.floor(Math.random() * (max - min) + min);
}
function Bug(x, y) {
this.x = x;
this.y = y;
this.jitter = 10;
this.speed = 1;
this.deg = 0;
this.rad = 0;
this.update = function() {
//update degrees
this.deg += randomRange(this.jitter, -this.jitter);
//convert degrees into radians
this.rad = this.deg * (Math.PI/180);
//update coordinates
this.x += this.speed * (Math.cos(this.rad));
this.y += this.speed * (Math.sin(this.rad));
};
this.draw = function() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fill();
};
}
【问题讨论】:
-
你应该/可以使用
ctx.clearRect(0, 0, canvas.width, canvas.height)来清除画布。
标签: javascript html animation canvas html5-canvas