这段代码如何绘制出三个圆圈?

时间:2016-01-27 14:33:34

标签: javascript

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

2 个答案:

答案 0 :(得分:1)

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

ceil(N/3)+floor(N/5)
ceil(N/3)+ceil(N/5)
floor((N+2)/3)+floor((N+14)/15)
floor(N/3)+floor(N/5)
floor(N/3)+ceilt(N/5)

答案 1 :(得分:0)

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