Rectangle example

Creating Shapes with HTML Canvas

Since HTML 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 the context we set. If you’re brand new to HTML canvas, start with our introduction article.

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

Creating Rectangles and Squares with HTML Canvas

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

  • 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.
Читайте также:  Структура языка html понятие элемента

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

If you want to learn about clearRect , read our tutorial on that here.

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 100×150 , 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 which 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 HTML Canvas

The easiest way to create a circle in HTML 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 counter clockwise (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 HTML 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 draw 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 counter clockwise 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(); 
  • We start by using moveTo to determine the starting point of our triangle.
  • Then, we draw a line from (20, 0) to (40, 30) — i.e. 20px to the right, and 30px down from our starting point.
  • Since this triangle will be symmetrical, we draw a 20px to the left, and 30px down, i.e. (0, 30).
  • Finally, we join our shape up by drawing a line back to our starting point, which was (20, 0).
  • 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.

More Tips and Tricks for HTML

Источник

CanvasRenderingContext2D: rect() method

The CanvasRenderingContext2D.rect() method of the Canvas 2D API adds a rectangle to the current path.

Like other methods that modify the current path, this method does not directly render anything. To draw the rectangle onto a canvas, you can use the fill() or stroke() methods.

Note: To both create and render a rectangle in one step, use the fillRect() or strokeRect() methods.

Syntax

The rect() method creates a rectangular path whose starting point is at (x, y) and whose size is specified by width and height .

Parameters

The x-axis coordinate of the rectangle’s starting point.

The y-axis coordinate of the rectangle’s starting point.

The rectangle’s width. Positive values are to the right, and negative to the left.

The rectangle’s height. Positive values are down, and negative are up.

Return value

Examples

Drawing a rectangle

This example creates a rectangular path using the rect() method. The path is then rendered using the fill() method.

HTML

JavaScript

The rectangle’s corner is located at (10, 20). It has a width of 150 and a height of 100.

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.rect(10, 20, 150, 100); ctx.fill(); 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

HTML5 Canvas Rectangle

To draw a rectangle, specify the x and y coordinates (upper-left corner) and the height and width of the rectangle. There are three rectangle methods :

html5 canvas: sample rectangle

  • fillRect()
  • strokeRect()
  • clearRect()

fillRect() Method

The fillRect() method is used to fill a rectangle in the current color, gradient, or pattern.

Remark : If the width or height parameter is zero, this method has no effect.

Example : HTML5 Canvas rectangle using fillRect() Method

The following web document fills a rectangle by fillStyle property.

rectangle with fillRect() method

        

strokeRect() Method

The strokeRect() method is used to fill a rectangle in the current color, gradient, or pattern.

ctx.strokeRect(x, y, width, height)
Parameters Type Description
x number The x-coordinate (in pixels), the upper-left corner of the rectangle in relation to the coordinates of the canvas.
y number The y-coordinate (in pixels), of the upper-left corner of the rectangle in relation to the coordinates of the canvas.
width number The width (in pixels), of the rectangle.
height number The height (in pixels), of the rectangle.

Example: HTML5 Canvas rectangle using fillRect() Method

The web document draws rectangles by using strokeStyle, lineJoin, and lineWidth for various effects.

HTML5 canvas strokeRect rectangle

      var canvas = document.getElementById("DemoCanvas"); if (canvas.getContext) 

clearRect() Method

The clearRect() method is used to clear a rectangle (erase the area to transparent black).

ctx.clearRect(x, y, width, height)

Example: HTML5 Canvas rectangle using clearRect() Method

The web document draws a series of rectangles using fillRect() and clearRect() methods.

HTML5 Canvas clearRect() method rectangle

        

Code Editor:

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью