我已經使用此代碼來改進我的原始版本。這是一個自動化的交通燈,繪製出三個圓圈,模擬英國交通燈的紅色,紅色+黃色,綠色序列。問題是我不知道它是如何繪製出三個圈子的。我知道drawLight()會繪製它們,但代碼告訴它在哪裏繪製它們?請向我解釋這一點,謝謝。這段代碼如何畫出三個圓圈?
<script>
var c = document.createElement('canvas'),
ctx = c.getContext('2d');
c.width = 150;
c.height = 300;
document.body.appendChild(c);
var cycle = 0,
colours = {
red: "#cc0000",
yellow: "#cccc00",
green: "#00cc00",
off: "#333333"
};
function drawLight(id,colour) {
// avoid repetition, use a function!
ctx.fillStyle = colours[colour];
ctx.beginPath();
ctx.arc(95, 50 + 100*id, 40, 0, Math.PI*2);
ctx.fill();
ctx.stroke();
}
function changelight(){
ctx.stokeStyle = "black";
ctx.lineWidth = 3;
// top light: red if cycle = 0 or 1, off otherwise
drawLight(0, cycle <= 1 ? 'red' : 'off');
// middle light: yellow if cycle = 3 (and 1 for UK lights, we have red+yellow before green), off otherwise
drawLight(1, cycle == 1 || cycle == 3 ? 'yellow' : 'off');
// bottom light: green if cycle = 2
drawLight(2, cycle == 2 ? 'green' : 'off');
// increment cycle
cycle = (cycle + 1) % 4;
}
// start the magic
setInterval(changelight,1000);
</script>
<br><br>
<button onclick="changelight()">Click</button>
''setInterval'每1秒鐘調用一次'changelight',在不同'cycle'值下輪流調用'drawLight'三次。如果「循環」爲0,則它繪製紅色光,如果它是1,則繪製黃色光,如果它是2,則繪製紅色光。然後它設置'cycle =(cycle + 1)%4',這意味着下一個值可以是0,1,2或3.這個catch就是'changelight'一次繪製一個圓圈,具體取決於'cycle'值。降低了你的問題,因爲你沒有盡力理解代碼。 – TeoMor
不要破壞你的帖子 –