DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Trending

  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • The Role of AI in Identity and Access Management for Organizations

Drawing Basic Shapes with HTML5 Canvas

HTML5 Canvas lets us draw basic shapes. Discover how drawing works and how to make basic shapes with HTML Canvas.

By 
Johnny Simpson user avatar
Johnny Simpson
DZone Core CORE ·
Apr. 01, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.0K Views

Join the DZone community and get the full member experience.

Join For Free

Since HTML5 Canvas is a graphic tool, it goes without saying that it allows us to draw shapes. We can draw new shapes using a number of different functions available to use via the context we set. 

In this guide, we'll cover how to make some of the most basic shapes with HTML5 Canvas — squares, rectangles, circles, and triangles.

Creating Rectangles and Squares with HTML5 Canvas

Squares and rectangles are easy to make in HTML5 Canvas. There are a number of different rect functions we can use to make shapes.

  • rect(x, y, width, height) — outlines where a rectangle or square should be, but does not fill it.
  • fillRect(x, y, width, height) — creates a rectangle and immediately fills it.
  • strokeRect(x, y, width, height) — creates a rectangle and immediately outlines it with a stroke. 

As you can see, all of these functions follow the same format - they have an x- and y-coordinate for where they start, and a width and height within the canvas. Let's look at some examples in code.

Clear Rectangle Function

Using rect() to Create a Rectangle

If we want to use rect() to create a rectangle, and then fill and stroke it, we need to define the fillStyle and strokeStyle. For example, the below code will create a rectangle starting at (10, 10), of dimensions 100x150, with a #b668ff background, and 5px wide white stroke:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

ctx.rect(10, 10, 100, 150);
ctx.fillStyle = '#b668ff';
ctx.strokeStyle = 'white';
ctx.lineWidth = 5;
ctx.fill();
ctx.stroke();


Using fillRect() to Create a Rectangle

fillRect lets us create a rectangle and automatically fill it with a specific color. That means we don't have to use fill() separately.

For example, the following will fill a rectangle of the same size as before, with a #b668ff background:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

ctx.fillStyle = '#b668ff';
ctx.fillRect(10, 10, 100, 150);


Using strokeRect() to create a rectangle

strokeRect() follows a similar format, only it will create a rectangle that is stroked automatically. For example, the below code will make a rectangle of the same dimensions and position as before, with a 5px wide #b668ff border/stroke:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

ctx.strokeStyle = '#b668ff';
ctx.lineWidth = 5;
ctx.strokeRect(10, 10, 100, 150);


Creating Circles in HTML5 Canvas

The easiest way to create a circle in HTML5 Canvas is to use the arc function. An arc doesn't have to draw a full circle, though - it can draw only part of a circle by changing the start and end angles. Let's look at the syntax of ctx.arc, and how to make a circle.

ctx.arc(x, y, radius, startAngle, endAngle, counterClockwise?)

  • x — refers to the x coordinate of the center of the circle.
  • y — refers to the y coordinate of the center of the circle.
  • radius — the radius of the arc we are drawing.
  • startAngle — the angle at which the arc starts (in radians).
  • endAngle — the angle at which the arc ends (in radians).
  • counterClockwise — whether the angle goes counterclockwise (default is false; can be set to true).

If we set our startAngle to 0 Radians, it will start at the center-right side of the circle. A circle is 2π radians in diameter. If we want to draw a full circle, our startAngle is 0, and our endAngle is 2π.

We can represent this in code using Math.PI * 2. Here is our code to draw a circle, with a 4px wide stroke in #b668ff, with a radius of 90px, where its center point is (100, 100):

let canvas = document.getElementById('canvas4');
let ctx = canvas.getContext('2d');

ctx.arc(100, 100, 100, 0, Math.PI * 2, false);
ctx.strokeStyle = '#b668ff';
ctx.lineWidth = 4;
ctx.stroke();


Creating Semi-Circles with HTML5 Canvas

Since we can use arc to draw circles and adjust our endAngle, we can also use it to draw a semi-circle. As a full circle is 2π in diameter, a semi-circle is only 1π radians. The only extra step we have to do here is drawing a line from the end of our semi-circle, back to the beginning again.

Since we are going to end at (10, 100) - as our radius is 90px, we draw a line with the lineTo function back to our starting point, which is (190, 100).

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

ctx.arc(100, 100, 90, 0, Math.PI * 1, false);
ctx.lineTo(190, 100);
ctx.fillStyle = '#b668ff';
ctx.fill();


We can flip our semi-circle by changing the counterclockwise option to true:

ctx.arc(100, 100, 90, 0, Math.PI * 1, true);


Creating Ovals with HTML Canvas

We can draw an oval in HTML5 canvas by using the ellipse() function. It works in a very similar way to arc(), except we have two radius options.

ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterClockwise?)

  • x - refers to the x coordinate of the center of the circle.
  • y - refers to the y coordinate of the center of the circle.
  • radiusX - the radius along the X axis of the arc we are drawing.
  • radiusY - the radius along the Y axis of the arc we are drawing.
  • rotation - how much we wish to rotate our ellipse shape, in radians.
  • startAngle - the angle at which the arc starts (in radians).
  • endAngle - the angle at which the arc ends (in radians).
  • counterClockwise - whether the angle goes counter clockwise (default is false, can be set to true).

Here is an example, using the same concepts as we did before with arc():

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

ctx.ellipse(100, 60, 90, 60, 0, 0, Math.PI * 2, false);
ctx.fillStyle = '#b668ff';
ctx.fill();


Creating Triangle Shapes with HTML Canvas

There is no built-in triangle function in Javascript, so we have to use the lineTo and moveTo function instead. All these functions do are draw lines on the context, to specific points.

We use moveTo to determine the starting position of our triangle, and then draw lines as appropriate to draw the shape of the triangle we want. Here is an example where we draw a triangle and fill it with #b668ff.

let canvas = document.getElementById('canvas8');
let ctx = canvas.getContext('2d');

ctx.moveTo(20, 0);
ctx.lineTo(40, 30);
ctx.lineTo(0, 30);
ctx.lineTo(20, 0);
ctx.fillStyle = '#b668ff';
ctx.fill();


Outcome:

  1. We start by using moveTo to determine the starting point of our triangle.
  2. Then, we draw a line from (20, 0) to (40, 30) - i.e. 20px to the right, and 30px down from our starting point.
  3. Since this triangle will be symmetrical, we draw a 20px to the left, and 30px down, i.e. (0, 30).
  4. Finally, we join our shape up by drawing a line back to our starting point, which was (20, 0).
  5. Then we fill it, and we have a triangle.

The lineTo() function can be used to draw many more complicated shapes in HTML Canvas, which are not built-in by default. Any custom polygons will use lineTo, such as Hexagons, Octagons, or even Parallelograms.

Conclusion

In this guide, we've covered how to make some simple shapes in HTML canvas: squares, rectangles, circles, and triangles. We've also touched upon the fact that lineTo can be used to draw a line anywhere on our canvas, allowing us to make more complicated shapes like hexagons and octagons. I hope you've enjoyed this article.

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!