【问题标题】:How does this code draw out three circles?这段代码如何画出三个圆圈?
【发布时间】: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


【解决方案1】:

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();

【讨论】:

  • 哪里说画三张?
  • changelight 调用drawLight 三次
  • 这是第一个:// top light: red if cycle = 0 or 1, off otherwise drawLight(0, cycle &lt;= 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'); cmets 是不言自明的。
  • @GigiSan 但是你的评论不清晰
  • 对不起,所以裁剪任何换行符... :(
【解决方案2】:

使用 HTML5 画布元素 (http://www.w3schools.com/html/html5_canvas.asp)。 arc 函数用于画圆。见:http://www.w3schools.com/tags/canvas_arc.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多