javascript - How does this code draw out three circles? -
i have used code improve original version. automated traffic light draws out 3 circles , simulates red, red+yellow, green sequence of british traffic light. problem have no idea how drawing out 3 circles. know drawlight() draws them code tells draw them? can please explain me thanks.
<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 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 uk lights, 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 magic setinterval(changelight,1000); </script> <br><br> <button onclick="changelight()">click</button>
see 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();
Comments
Post a Comment