用javaScript绘制内圈



有人能解释为什么画内圈吗?我的代码做圆圈,当它完成 360 度时,它会再次绘制整个画布。我以为它只会在新圆圈的边界上画球。只是为了让它更清楚(也许(。我只想画圆圈,而不是机芯的中心。这个想法是在圆圈的运动上与球形成一个轮廓,并每隔360度制作一个新的轮廓(我称之为drawStage的原因(。 问题的图像:

https://i.stack.imgur.com/vF8fJ.jpg

https://i.stack.imgur.com/tSRHS.jpg

我涂红色的部分是问题所在

HTML CODE (tela.html(

<!DOCTYPE html>
<html>
<title>JS Game</title>
<body>
<h1>JavaScript Game</h1>
<canvas id="tela"></canvas>
<script src="Game.js"></script>
</body>
</html>

JavaScript 代码 (Game.js(

console.log("Starting Game");
var canvas = document.querySelector('#tela');
var stageCollor = 'black';
var ballColor = 'grey';
console.log(canvas);
var stage = canvas.getContext('2d');
var ball = canvas.getContext('2d');
drawStage();
let distanceFromCenter = 0;
let startWidth = canvas.width/2;
let startHeight = canvas.height/2;
let ballRadius = 10;
let startAngle = 0;
let endAngle = 2 * Math.PI;
let turnedAngle = 0;
let piTurnedAngle= 0;
ball.arc(startWidth, startHeight, ballRadius, startAngle, endAngle);
ball.stroke();//draw
ball.fillStyle = ballColor;
ball.lineWidth = 1;
ball.fill();
setInterval(move,40);//magic
function move() {
//drawStage();
turnedAngle = turnedAngle +5;
piTurnedAngle = turningMovement(turnedAngle);
distanceFromCenter = distanceFromCenter +0.0125;
startWidth = startWidth + distanceFromCenter*Math.cos(piTurnedAngle);
startHeight = startHeight - distanceFromCenter*Math.sin(piTurnedAngle);
drawBall();
}
function drawBall() {   
ball.arc(startWidth, startHeight, ballRadius, startAngle, endAngle);
ball.stroke();//draw
ball.fillStyle = ballColor;
ball.lineWidth = 1;
ball.fill();
console.log('d - ' + startWidth);
}
function eraseBall() {  
ball.arc(startWidth, startHeight, ballRadius, startAngle, endAngle);
ball.stroke();//draw
ball.fillStyle = stageCollor;
ball.lineWidth = 1;
ball.fill();
console.log('e - ' + startWidth);
}
function drawStage(){
canvas.width = 800;
canvas.height = 600;
stage.fillStyle = stageCollor;
stage.fillRect(0,0,canvas.width, canvas.height);
stage.beginPath();
}
function turningMovement(angle){
if(angle>360){
angle = angle%360;
if (angle == 0){
drawStage();
}
}
newAngle = angle/180;
newAngle = newAngle*Math.PI;
return newAngle;
}

发生这种情况是因为画布填满了在各种球之间绘制的路径。您定期在drawBall()内呼叫arc(),但从不呼叫beginPath()endPath()

这是我能想到的最简单的例子(使用你的JS代码(来说明这个问题:删除setInterval()行,这样动画就不会开始。然后在控制台中运行以下命令:

drawStage();
turnedAngle = 10; startWidth = 404.45625508238027; startHeight = 299.2142419960571; drawBall();
turnedAngle = 70; startWidth = 423.114564032465; startHeight = 280.45069066017015; drawBall();
turnedAngle = 150; startWidth = 408.03409582988786; startHeight = 248.52411884675797; drawBall();

请注意在 3 个球上绘制的三角形。

要解决此问题,只需在arc()呼叫之前添加ball.beginPath()

最新更新