【发布时间】:2016-05-04 13:39:43
【问题描述】:
我已使用此代码来改进我的原始版本。它是一个自动红绿灯,画出三个圆圈,模拟英国红绿灯的红、红+黄、绿序列。问题是我不知道它是如何画出三个圆圈的。我知道 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,然后依次调用drawLight三次,使用不同的cycle值。如果cycle为 0,则绘制红灯,如果为 1,则绘制黄灯,如果为 2,则绘制红灯。然后它设置cycle = (cycle + 1) % 4,这意味着下一个值可以是0、1、2或3。问题是changelight根据cycle的值一次绘制1个圆圈。否决了您的问题,因为您没有尽最大努力理解代码。
标签: javascript