所以我试图在圆形轨道上围绕同一个中心创建两个圆圈,但是当我输入'ctx.clearRect(0,0,w,h)'(第18行)时,它会移除内圈和保持外面的一个。如果没有clearRect线,它只会将圆圈保持在屏幕上,留下一个圆圈,因为它的轨迹(最终变成一个大圆圈)。有没有办法防止内圈消失?
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var dd2 = 2.26;
var angle = 0;
var angle2 = 0;
var cx = 670;
var cy = 400;
var radius = 200;
var radius2 = 300;
ctx.fillStyle = "white";
ctx.strokeStyle = "blue";
(function () {
"use strict";
function draw(x, y) {
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.beginPath();
ctx.beginPath();
ctx.arc(x - 50 / 2, y - 30 / 2, 75, 75, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.restore();
};
var fps = 60;
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / fps);
};
})();
function animate() {
setTimeout(function () {
requestAnimFrame(animate);
ctx.beginPath();
angle += Math.acos(1 - Math.pow(dd / radius, 2) / 2);
var newX = cx + radius * Math.cos(angle),
newY = cy + radius * Math.sin(angle);
draw(newX, newY);
ctx.arc(cx, cy, radius, radius, 0, Math.PI * 2);
angle2 += Math.acos(1 - Math.pow(dd2 / radius2, 2) / 2);
var newX2 = cx + radius2 * Math.cos(angle2),
newY2 = cy + radius2 * Math.sin(angle2);
draw(newX2, newY2);
ctx.arc(cx, cy, radius2, 0, Math.PI * 2);
ctx.closePath();
}, 1000 / fps);
}
animate();
}());