我有一個家庭作業,要求我列印兩種不同大小的交替圓形顏色。最終結果將如下所示:

現在,我正在努力在紅色圓圈上列印藍色圓圈,這是我寫的代碼:
canvas = document.getElementById("testCanvas");
context = canvas.getContext("2d");
centerX = canvas.width / 2;
centerY = canvas.height / 2;
//Creates a red color circle
context.arc(centerX, centerY, 200, 0, 2 * Math.PI);
context.fillStyle = 'red';
context.fill();
//Creates a blue color circle on top of the red color circle
context.arc(centerX, centerY, 150, 0, 2 * Math.PI);
// context.lineWidth=5;
context.fillStyle = 'blue';
context.stroke();
<canvas id="testCanvas" width="400" height="400"></canvas>
我在使用最后一段代碼時遇到了問題,因為如果我在最后一行代碼上說 fill(),那么藍色將主導畫布。任何幫助將不勝感激。提前致謝。
uj5u.com熱心網友回復:
您必須回圈并繪制增加/減少半徑的圓圈。并在回圈內切換顏色。每次繪制一個圓圈時,您都需要使用它beginPath()來開始和closePath()防止重疊。
const canvas = document.getElementById("testCanvas");
const context = canvas.getContext("2d");
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
let radius = centerX;
let color = "red";
while (radius > 0) {
context.beginPath();
context.fillStyle = color;
context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
context.fill();
context.closePath();
color = color === "red" ? "blue" : "red";
radius -= 25;
}
<canvas id="testCanvas" width="400" height="400"></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443849.html
標籤:javascript
