Javascript 这个代码是如何画出三个圆的?

Javascript 这个代码是如何画出三个圆的?,javascript,Javascript,我已使用此代码来改进我的原始版本。它是一个自动交通灯,画出三个圆圈,模拟英国交通灯的红色、红色+黄色、绿色序列。问题是我不知道它是如何画出这三个圆圈的。我知道drawLight()会绘制它们,但是告诉它在哪里绘制它们的代码在哪里?请给我解释一下,谢谢 <script> var c = document.createElement('canvas'), ctx = c.getContext('2d'); c.width = 150;

我已使用此代码来改进我的原始版本。它是一个自动交通灯,画出三个圆圈,模拟英国交通灯的红色、红色+黄色、绿色序列。问题是我不知道它是如何画出这三个圆圈的。我知道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>

var c=document.createElement('canvas'),
ctx=c.getContext('2d');
c、 宽度=150;
c、 高度=300;
文件.正文.附件(c);
var循环=0,
颜色={
红色:“cc0000”,
黄色:“CC00”,
绿色:“00cc00”,
关:“333333”
};
功能抽油灯(id、颜色){
//避免重复,使用函数!
ctx.fillStyle=颜色[颜色];
ctx.beginPath();
弧(95,50+100*id,40,0,数学PI*2);
ctx.fill();
ctx.stroke();
}
函数changelight(){
ctx.stokeStyle=“黑色”;
ctx.lineWidth=3;
//顶灯:如果循环=0或1,则为红色,否则为关闭
牵引灯(0,周期见


使用HTML5画布元素()。arc函数用于绘制圆圈。请参见:

它说的是在哪里绘制三个?
changelight
调用
drawLight
三次这里是第一次:
//顶部指示灯:如果cycle=0或1,则为红色,否则为关闭(0,cycle@GigiSan,但您的评论不清晰,所以请删除任何新行…:(
setInterval
每1秒调用一次
changelight
,它在轮到它的时候调用
drawLight
三次,使用不同的
cycle
值。如果
cycle
为0,它将显示红灯,如果为1,它将显示黄灯,如果为2,它将显示红灯。然后它设置
cycle=(cycle+1)%4
这意味着下一个值可以是0、1、2或3。关键是
changelight
根据
循环
值一次画一个圆。由于您没有表现出理解代码的最小努力,所以对您的问题投了否决票。
ctx.beginPath();
//       x           y       radius     startAngle,  endAngle
ctx.arc(95,    50 + 100*id,    40,         0,         Math.PI*2);
ctx.fill();
ctx.stroke();