Search code examples
javascriptdrawing

MoveTo drawing a line?


<script>

function myFunction2() {


side1 = prompt("Enter the X axis of the bottom side")

side2 = prompt("Enter the X axis of the left side")

side3 = prompt("Enter the X axis of the right side")



var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(0, 200);

context.lineTo(side1, 200);
context.stroke();
context.lineTo(side2, 100);
context.stroke();
context.lineTo(side3, 200);
context.stroke();
context.closePath();

}

</script>

I'm trying to make a triangle so that a user can enter its sides lengths, but this doesn't work. What am I doing wrong?


Solution

  • context.moveTo(0, 200); moves your 'pen' (starting point) to 0, 200 which becomes the starting point for your first line. Your first line ends at side1, 200. This probably isn't what you want.

    Rewrite your code like this:

    context.beginPath();
    
    context.moveTo(side1, 200); // Start point for line 1
    context.lineTo(side2, 100); // End point for line 1, start for line 2
    context.stroke();
    context.lineTo(side3, 200); // End point for line 2, start for line 3
    context.stroke();
    context.lineTo(side1, 200); // End point for line 3, back where we started
    context.stroke();
    context.closePath();