How to color line in canvas?

Member

by ryleigh , in category: Javascript , 4 months ago

How to color line in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 4 months ago

@ryleigh 

To color a line in a canvas element, you can use the strokeStyle property of the canvas context. Here's an example of how to color a line in canvas:

  1. First, select the canvas element and get its 2d drawing context:
1
2
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');


  1. Set the color for the line using the strokeStyle property:
1
ctx.strokeStyle = 'red'; // set the line color to red


  1. Draw a line on the canvas using the moveTo and lineTo methods:
1
2
3
4
ctx.beginPath();
ctx.moveTo(50, 50); // move to the starting point of the line
ctx.lineTo(150, 100); // draw a line to the ending point
ctx.stroke(); // draw the line with the specified color


This will draw a red line from the point (50, 50) to the point (150, 100) on the canvas.


You can change the color of the line by setting the strokeStyle property to a different color before drawing the line. You can also change the line width and other properties using the canvas context.