2
$\begingroup$

When I was doing some graphic designing with JavaScript, I saw this strange behaviour.
When I ran the following code (with proper HTML and JavaScript of course),

context.lineTo(100, 100);
context.lineTo(200, 200);
context.stroke();

The result was a straight line from (100, 100) to (200, 200), which I wasn't expecting. I expected that nothing would be drawn. I think this would only happen with the following code:

context.beginPath();
context.moveTo(100, 100);
context.lineTo(200, 200);
context.stroke();

Is my thinking wrong? Why is it happening so? Can anyone explain?

$\endgroup$
2
$\begingroup$

Straight from the specification of lineTo:

If the object's path has no subpaths, then ensure there is a subpath for (x, y).

And "ensure that there is a subpath" links to this bit:

When the user agent is to ensure there is a subpath for a coordinate (x, y) on a path, the user agent must check to see if the path has its need new subpath flag set. If it does, then the user agent must create a new subpath with the point (x, y) as its first (and only) point, as if the moveTo() method had been called, and must then unset the path's need new subpath flag.

In short, if you call lineTo without an explicit beginPath, then a new path is created implicitly, with the given point as its starting point.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.