这段代码是如何画出三个圆圈的

How does this code draw out three circles?

本文关键字:三个 段代码 代码 何画出      更新时间:2023-09-26

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

请参阅 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc

ctx.beginPath();
//       x           y       radius     startAngle,  endAngle
ctx.arc(95,    50 + 100*id,    40,         0,         Math.PI*2);
ctx.fill();
ctx.stroke();

使用 HTML5 Canvas 元素 (http://www.w3schools.com/html/html5_canvas.asp)。弧函数用于绘制圆圈。请参阅: http://www.w3schools.com/tags/canvas_arc.asp