HTML5 Canvas Line Cap Tutorial Example code

HTML5 Canvas Line Cap Tutorial Example code HTML, CSS, javascript


This is an article about HTML5 Canvas Line Cap styles and an example code snippet in HTML and JavaScript demonstrating how to use different line cap styles in the canvas element.


Understanding HTML5 Canvas Line Cap Styles


In HTML5 Canvas, the lineCap property is used to set the style of the endpoints of a line. There are three possible line cap styles: round, square, and butt.


Round Line Cap (round):

 When the lineCap property is set to 'round', the endpoints of a line are rounded, creating a smooth, circular endpoint. This style is commonly used for drawing lines that represent paths or curves.


Square Line Cap (square):

The 'square' line cap style adds a square extension beyond the endpoints of the line. This extension is half the line's thickness. It's useful when you want a line to extend slightly beyond its defined endpoints.


Butt Line Cap (butt):

The 'butt' line cap style is the default setting. Lines with this cap style have square endpoints that precisely meet the defined endpoints without any extensions.


Now, let's look at an example code snippet to understand how to implement these line cap styles in HTML and JavaScript.


HTML 


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>HTML5 Canvas Line Cap Styles</title>

  <style>

    canvas {

      border: 1px solid black;

    }

  </style>

</head>

<body>

  <canvas id="myCanvas" width="400" height="200"></canvas>

  <script src="script.js"></script>

</body>

</html>


Canvas HTML5 JAVASCRIPT example


In this example, we first set the line width to 10. Then, we draw three lines with different line cap styles ('round', 'square', and 'butt'). The canvas element is defined in HTML with the ID myCanvas, and the JavaScript code in script.js handles the drawing operations.


You can copy this code into separate HTML, CSS, and JavaScript files and open the HTML file in your web browser to see the different line cap styles in action.


const canvas = document.getElementById('myCanvas');

const ctx = canvas.getContext('2d');


// Set line width

ctx.lineWidth = 10;


// Draw lines with different line cap styles

ctx.strokeStyle = 'blue';

ctx.lineCap = 'round';

ctx.beginPath();

ctx.moveTo(50, 50);

ctx.lineTo(150, 50);

ctx.stroke();


ctx.strokeStyle = 'green';

ctx.lineCap = 'square';

ctx.beginPath();

ctx.moveTo(50, 100);

ctx.lineTo(150, 100);

ctx.stroke();


ctx.strokeStyle = 'red';

ctx.lineCap = 'butt';

ctx.beginPath();

ctx.moveTo(50, 150);

ctx.lineTo(150, 150);

ctx.stroke();


OUTPUT:


HTML5 Canvas Line Cap Styles

Comments :

Post a Comment