As planned, after the first mouse click, the first point of the apex of the triangle appears. After the second two points must be connected by a segment.
var X, Y // ΠΊΠΎΠΎΡΠ΄ΠΈΠ½Π°ΡΡ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΡΠ»Π΅Π΄ΡΡΡΠ΅Π³ΠΎ Π½Π°ΠΆΠ°ΡΠΈΡ ΠΌΡΡΠΈ var triCount = 0 // ΡΠΊΠΎΠ»ΡΠΊΠΎ Π²Π΅ΡΡΠΈΠ½ ΡΡΠ΅ΡΠ³ΠΎΠ»ΡΠ½ΠΈΠΊΠ° ΡΠΆΠ΅ ΠΎΡΠΌΠ΅ΡΠ΅Π½ΠΎ ... switch(triCount) { // ΠΏΠ΅ΡΠ²ΡΠΉ ΠΊΠ»ΠΈΠΊ ΠΌΡΡΡΡ case 0: ctx.beginPath(); ctx.rect(X, Y, 1, 1); // ΠΎΡΠΌΠ΅ΡΠ°Π΅ΠΌ ΠΏΠ΅ΡΠ²ΡΡ Π²Π΅ΡΡΠΈΠ½Ρ ΡΡΠ΅ΡΠ³ΠΎΠ»ΡΠ½ΠΈΠΊΠ° ctx.stroke(); // Π΄Π΅Π»Π°Π΅ΠΌ ΡΠΎΡΠΊΡ Π²ΠΈΠ΄ΠΈΠΌΠΎΠΉ triCount++; // ΡΠ²Π΅Π»ΠΈΡΠΈΠ²Π°Π΅ΠΌ triCount Π΄ΠΎ 1 break; // Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ ΠΊΠ½ΠΎΠΏΠΊΡ ΠΌΡΡΠΈ Π²ΠΎ Π²ΡΠΎΡΠΎΠΉ ΡΠ°Π· ΠΏΠΎΠ»ΡΡΠ°Ρ X ΠΈ Y Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ Π²Π΅ΡΡΠΈΠ½Ρ // ΠΏΠΎΠΏΠ°Π΄Π°Π΅ΠΌ Π² CASE1 case 1: ctx.lineTo(X, Y); // Π½Π΅ ΡΠΈΡΡΠ΅Ρ Π»ΠΈΠ½ΠΈΡ ΠΎΡ ΠΏΡΠ΅Π΄ΡΠ΄ΡΡΠ΅ΠΉ ΡΠΎΡΠΊΠΈ ctx.stroke(); break; } The transition to the second CASE is correct, checked. Variables work correctly: X and Y change after each mouse click. If you put all the code together inside a single CASE, it draws as needed. Tried without BRAKE (what if?) - does not help. Tried closePath () in the second CASE - does not help.
(addition) When I wrote this code apart from the rest of the script, it all worked, thanks for offering to create an example. Now I know for sure what should work, I will look for a mistake in somewhere else. Here is a working example:
<!doctype html> <html> <body> <canvas id="canvas" width="600" height="400"></canvas> <script> window.addEventListener('load', function() { var triCount = 0; var X = 0; var Y = 0; var ctx = canvas.getContext('2d'); canvas.addEventListener('mousedown', onMouseDown, false); function onMouseDown(e) { X = e.offsetX; Y = e.offsetY; switch(triCount) { case 0: ctx.beginPath(); ctx.rect(X, Y, 1, 1); ctx.stroke(); triCount++; break; case 1: ctx.lineTo(X, Y); ctx.stroke(); break; } } }); </script> </body> </html> Everything turned out to be simple, when you clicked the mouse, even before SWITCH in the script was beginPath (). Thus, without finishing one piece, I started another.
ctxcreated? Language - javascript? Create a working example using the "Fragment of code on ..." editor button - Igor