How to draw a line on an HTML5 canvas?
To draw HTML5 canvas lines, you need to follow the following steps: 1. Create a canvas element with id and width and height in HTML; 2. Use JavaScript to get the element and call getContext('2d') to get the 2D rendering context; 3. Call beginPath() to start the path, moveTo() set the start point, lineTo() set the end point, and stroke() draw the line; 4. You can customize the line style through attributes such as lineWidth, strokeStyle and lineCap; always remember to call beginPath() before drawing a new line, and the line coordinates are based on the origin of the upper left corner of canvas, and the lines will be displayed after calling stroke().
Drawing a line on an HTML5 canvas is straightforward once you understand the basic steps. You need a <canvas></canvas>
element and a bit of JavaScript to define the line's start and end points.

Here's how to do it:
1. Set up the canvas element
First, add a <canvas></canvas>
tag in your HTML. Give it an id
so you can reference it in JavaScript, and set its width
and height
.

<canvas id="myCanvas" width="500" style="max-width:90%"></canvas>
2. Get the 2D rendering context
In JavaScript, you need to get the canvas context to draw on it. The 2D context provides drawing functions.
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
3. Draw the line
Use the following steps in order:

- Call
beginPath()
to start a new path. - Use
moveTo(x, y)
to set the starting point. - Use
lineTo(x, y)
to define the end point. - Call
stroke()
to actually render the line.
ctx.beginPath(); ctx.moveTo(50, 50); // Start point (x=50, y=50) ctx.lineTo(200, 100); // End point (x=200, y=100) ctx.stroke(); // Draw the line
Customize the line appearance
You can adjust the line's style using these properties:
-
ctx.lineWidth
– sets the thickness of the line. -
ctx.strokeStyle
– sets the color or gradient. -
ctx.lineCap
– defines the shape at the ends of the line ('butt'
,'round'
,'square'
).
Example with styling:
ctx.beginPath(); ctx.moveTo(50, 50); ctx.lineTo(200, 100); ctx.lineWidth = 5; ctx.strokeStyle = 'blue'; ctx.lineCap = 'round'; ctx.stroke();
Notes to remember
- Always call
beginPath()
before starting a new line to avoid connecting to previous paths. - The line won't appear until you call
stroke()
. - Coordinates are relative to the top-left corner of the canvas (0,0).
That's it. You now have a visible line on your canvas. From here, you can build more complex drawings by combining multiple lines or shapes.
The above is the detailed content of How to draw a line on an HTML5 canvas?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

First create hidden audio elements and build a custom control UI, and then connect functions such as playback, pause, progress adjustment and volume control to the audio API through JavaScript to achieve a fully personalized audio player.

SSEenablesreal-time,unidirectionalserver-to-clientupdatesviaHTTP;useEventSourceinJavaScripttoconnect,handlemessageswithonmessage,setserverresponsetypetotext/event-stream,formatdatawith"data:"and"\n\n",andoptionallyincludeeventIDsf

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

UsesemanticHTMLelementslikeandfornativefocusabilityandkeyboardsupport.EnsurelogicaltaborderandvisiblefocusindicatorsviaCSS.Programmaticallymanagefocusindynamiccontentlikemodalsusingelement.focus(),trappingfocusinsideandreturningitafterclosure.ApplyAR

ThetimeelementinHTML5representsdatesandtimesinamachine-readableformat,enhancingaccessibilityandSEO;usethedatetimeattributewithISO-formattedvaluestoprovidesemanticmeaning,especiallyforhuman-friendlytextordurations,ensuringconsistentinterpretationbymac

UsethepatternattributeinHTML5inputelementstovalidateagainstaregex,suchasforpasswordsrequiringnumbers,uppercase,lowercase,andminimumlength;pairwithtitleforuserguidanceandrequiredfornon-emptyenforcement.

To make HTML5 image map responsive, you can dynamically scale coordinates through JavaScript or absolutely position the overlay element using CSS; first make sure the image itself is responsive, and then recalculate the area area coordinates according to the original and current size ratio through JavaScript when page loading and window adjustment, or use a transparent link to cover the image with percentage positioning to achieve cross-device adaptation, and ultimately ensure that the interactive area is correctly scaled with the image. The two methods have applicable scenarios. The JavaScript solution is compatible with the original structure, and the CSS solution is simpler and requires no scripts. It should be selected according to project needs, and both need to test the multi-screen effect and ensure that the touch area is large enough. It is recommended to use JavaScript method for a simple layout of complex maps.

Use or embed PDF; it is simple and direct, supports alternate content, has good compatibility and can be removed from borders, and choose according to your needs.
