Line Styles:
Line styles refer to the appearance of the stroke applied to a path. In HTML5 Canvas, you can set line styles using the strokeStyle property. This property can accept color values, gradients, or patterns.
Solid Color Line:
context.strokeStyle = 'red'; // Sets the stroke color to red
Gradient Line:
const gradient = context.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'blue');
gradient.addColorStop(1, 'green');
context.strokeStyle = gradient; // Sets the stroke to a linear gradient from blue to green
Pattern Line:
javascript
Copy code
const img = new Image();
img.src = 'pattern.png';
img.onload = () => {
const pattern = context.createPattern(img, 'repeat');
context.strokeStyle = pattern; // Sets the stroke to a pattern created from an image
}
Line Joins:
Line joins define how two connected lines or segments are joined at their intersection points. In HTML5 Canvas, you can set line joins using the lineJoin property.
Miter Join:
context.lineJoin = 'miter';
Round Join:
context.lineJoin = 'round';
Bevel Join:
context.lineJoin = 'bevel';
Line Caps:
Line caps define the style of endpoints (caps) of a line when it doesn't form a closed shape. In HTML5 Canvas, you can set line caps using the lineCap property.
Butt Cap:
context.lineCap = 'butt';
Round Cap:
context.lineCap = 'round';
Square Cap:
context.lineCap = 'square';
Examples:
Let's combine these concepts into an example:
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
// Line styles
context.strokeStyle = 'red';
context.lineWidth = 5;
// Line joins
context.lineJoin = 'round';
// Line caps
context.lineCap = 'round';
// Draw a path with line styles, joins, and caps
context.beginPath();
context.moveTo(50, 50);
context.lineTo(150, 100);
context.lineTo(250, 50);
context.stroke();
In this example:
- Line style is set to red with a line width of 5 pixels.
- Line join is set to round, so corners will have a rounded appearance.
- Line cap is set to round, so endpoints will have a rounded cap.
Practice Excercise Practice now