Sitemap / Advertise

Information



Tags



Share

How to draw geometrical shapes in HTML Canvas via JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

The HTML canvas element allows us to create graphics on the supported browser via JavaScript. As you define the sizes of the canvas, you can draw patterns, shapes or even images from edges to edges. In other words, your drawings are confined by the canvas itself despite the fact that a canvas has no content or no border by default.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.(1)

Furthermore, you can create basic games by using polygons and geometrical shapes in a canvas.

Code

In this article, I only show to draw basic geometrical shapes. First of all, create a canvas element like this to display shapes:

<canvas id="Canvas" width="300px" height="300px" style="border:2px solid white;"></canvas>

On JavaScript code, implement the getContext('2d') method to draw shapes in a context.

To draw a circle, add the beginPath() method along with the arc() method. And, to fill the circle add the fillStyle() method along with the fill() method.

In the arc() method, define the center point position and the radius.

To draw a rectangle, add the rect() method and define the x-coordinate of the upper-left corner, the y-coordinate of the upper-left corner, the width and the height.

Use the closePath() method to fill graphics with different colors.

There is no function or no method to draw a triangle in a a canvas thus use the moveTo() method and the lineTo() method.


var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext('2d');
// Circle.
ctx.beginPath();
ctx.fillStyle = "black";
ctx.arc(150, 60, 50, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
// Rectangle.
ctx.beginPath();
ctx.fillStyle = "green";
ctx.rect(100 ,130, 100, 50);
ctx.fill();
ctx.closePath();
// Triangle.
ctx.beginPath();
ctx.fillStyle = "yellow";
ctx.moveTo(150, 200);
ctx.lineTo(200, 250);
ctx.lineTo(100, 250);
ctx.lineTo(150, 200);
ctx.fill();
ctx.closePath();

Result:



References

(1) https://www.w3schools.com/html/html5_canvas.asp