[英]Painting inner circle with javaScript
有人可以解釋為什么要繪制內圈嗎? 我的代碼制作圓圈,當它完成 360 度時,它會再次繪制整個畫布。 我以為它只會在新圓圈的邊界上畫球。 只是為了讓它更清楚(也許)。 我只想畫圓圈而不是運動的中心。 這個想法是用球在圓圈的運動上形成一個輪廓,然后每 360 度創建一個新的輪廓(我稱之為 drawStage 的原因)。 問題圖片:
我塗紅色的部分是問題
HTML 代碼 (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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.