line

Category:Canvas

line(x1, y1, x2, y2)

Category: Canvas

Draws a line on the active canvas from (x1, y1) to (x2, y2).

You can draw many things with the basic canvas drawing functions of circle, line and rect. For line(), the (x1, y1) to (x2, y2) coordinates specify the endpoints of the line, relative to the top-left corner of the canvas (x:0 y:0). Lines are drawn using the current stroke width and current stroke color.

When drawing thick lines, the line coordinates define the center of the line. The ends of the line will be rounded, forming semi-circles beyond the ends of the line.

Examples


//Draw a diagonal line across the screen.
createCanvas("canvas1");
line(0, 0, 320, 480);

Example: Small Window Lines and shapes drawn outside the bounds of the canvas are not totally visible.

// Lines and shapes drawn outside the bounds of the canvas are not totally visible.
createCanvas("canvas1", 50, 50);
line(0, 0, 320, 480);

Example: Two Lines Draw two lines with different stroke width showing how the stroke width affects how the line is drawn.

// Draw two lines with different stroke width showing how the stroke width affects how the line is drawn.
createCanvas("canvas1");
setStrokeColor("lightblue");
setStrokeWidth(20);
line(20, 50, 300, 50);
setStrokeColor("black");
setStrokeWidth(1);
line(20, 50, 300, 50);

Example: Random Line Art Draw 100 random lines, head to tail.

// Draw 100 random lines, head to tail.
createCanvas("canvas1");
var x1=randomNumber(0,320);
var y1=randomNumber(0,480);
var x2=randomNumber(0,320);
var y2=randomNumber(0,480);
for (var i = 0; i < 100; i++) {
  line(x1, y1, x2, y2);
  x1=x2;
  y1=y2;
  x2=randomNumber(0,320);
  y2=randomNumber(0,480);  
}

Syntax

line(x1, y1, x2, y2)

Parameters

Name Type Required? Description
x1 number Yes The x position on the canvas in pixels of the beginning of the line.
y1 number Yes The y position on the canvas in pixels of the beginning of the line.
x2 number Yes The x position on the canvas in pixels of the end of the line.
y2 number Yes The y position on the canvas in pixels of the end of the line.

Returns

No return value. Outputs to the display only.

Tips

  • A canvas element must be created before a line can be drawn. Create a canvas element in Design mode first, or call createCanvas() before calling line.
  • If you're having trouble getting a line to show up, make sure that you're trying to draw the line within the bounds of the active canvas.
  • Change the width of the line and color of the line used to draw all subsequent liness using setStrokeWidth, setStrokeColor.

Found a bug in the documentation? Let us know at documentation@code.org

Found a bug in the documentation? Let us know at documentation@code.org