Startec

Startec

Drawing basic 2D shapes on a canvas.

Mai 19, às 17:48

·

4 min de leitura

·

0 leituras

Hello ūüĎč, Welcome back. In our previous lesson, we discussed what 2D shapes are, what a canvas is, and how to use coordinates on a canvas. In this tutorial, we will be drawing basic shapes. We will work on...
Drawing basic 2D shapes on a canvas.

Cover image for Drawing basic 2D shapes on a canvas.

Hello ūüĎč, Welcome back. In our previous lesson, we discussed what 2D shapes are, what a canvas is, and how to use coordinates on a canvas.

In this tutorial, we will be drawing basic shapes. We will work on improving our understanding of drawing shapes on our canvas.

Before we begin drawing, there are a few things you should know about using a canvas.

do's

  • Remember to always close your canvas with the </canvas> tag.
  • Sketch what you want to draw on a piece of paper so you will know where to put your coordinates.

don'ts

  • The size of the shape you're drawing should be no larger than the size of your canvas. If your object is larger than your canvas, the area that the canvas cannot contain will not be shown. The diagram below shows what happens when the canvas is smaller than the drawing.

error

result

Primitive shapes.

<canvas> supports only two primitive shapes:

  • rectangles and
  • paths (lists of points connected by lines). All other shapes are created by combining one or more paths.

Drawing a rectangle.

Because a rectangle is a primitive shape on canvas, it has its own set of drawing methods. There are three functions on the canvas that draw rectangles:

  • fillRect(x, y, width, height). This method creates a filled rectangle.

  • strokeRect(x, y, width, height). This creates the rectangle's outline.

  • clearRect(x, y, width, height). Clears the chosen rectangular region, making it transparent.

These three functions all use the same parameters. x and y define the top-left corner of the rectangle's position on the canvas (relative to the origin). The width and height define the size of the rectangle.

html

In our script file.

script

Drawing other shapes.

In contrast to the rectangle, every other shape must be created by joining one or more paths. A path, as we know, is a list of points connected by lines.

Let's draw a line to see what a path is.

line
code

line

A point, as shown in the diagrams above, is made up of an x and y coordinate. A path is formed by connecting these points with a line.

another example

line2
code

line2

From our codes above, we noticed new methods:

  • beginPath()
  • lineTo() and
  • stroke()

beginPath() Makes a new path.

lineTo() Adds a new point to the canvas.

stroke() Draws the shape by tracing its outline.

Shape 1: a triangle

code

triangle
result

triangle

Shape 2: an arrow

code

arrow
result

arrow

Shape 3: a star

code

star
result

star

At the end of this lesson, we learned how to draw some simple shapes. In our next topic, we'll look at adding color to our forms to make them more dynamic.
Please leave a comment with an image of a shape you created on your canvas.


Continue lendo

Showmetech

Motorola Razr Plus é o novo dobrável rival do Galaxy Z Flip
Ap√≥s duas tentativas da Motorola em emplacar ‚ÄĒ novamente ‚ÄĒ telefones dobr√°veis, eis que temos aqui a terceira, e aparentemente bem-vinda, tentativa. Estamos falando do Motorola Razr Plus, um smartphone...

Hoje, às 15:20

DEV

Mentoring for the LGBTQ+ Community
Once unpublished, all posts by chetanan will become hidden and only accessible to themselves. If chetanan is not suspended, they can still re-publish their posts from their dashboard. Note: Once...

Hoje, às 15:13

TabNews

IA: mais um arrependido / Déficit de TI / Apple: acusação grave · NewsletterOficial
Mais um pioneiro da IA se arrepende de seu trabalho: Yoshua Bengio teria priorizado seguran√ßa em vez de utilidade se soubesse o ritmo em que a tecnologia evoluiria ‚Äď ele junta-se a Geoffr...

Hoje, às 14:37

Hacker News

The Analog Thing: Analog Computing for the Future
THE ANALOG THING (THAT) THE ANALOG THING (THAT) is a high-quality, low-cost, open-source, and not-for-profit cutting-edge analog computer. THAT allows modeling dynamic systems with great speed,...

Hoje, às 14:25

TabNews

[DISCUS√ÉO/OPINI√ēES] ‚Äď Outsourcing! O que, para quem, por que sim, por que n√£o! ¬∑ dougg
Quero tentar trazer nesta minha primeira publicação, uma mistura de um breve esclarecimento sobre o que são empresas de outsourcing, como elas funcionam e ganham dinheiro, mas também, ven...

Hoje, às 13:58

TabNews

Duvida: JavaScript - Desenvolver uma aplicação que vai ler um arquivo *.json · RafaelMesquita
Bom dia a todos Estou estudando javascript e me deparei com uma dificuldade e preciso de ajuda *Objetivo do estudo: *desenvolver uma aplicação que vai ler um arquivo *.json Conteudo do in...

Hoje, às 13:43

Showmetech

Automatize suas negocia√ß√Ķes com um rob√ī de criptomoedas
√ćndice Como o rob√ī de criptomoedas Bitsgap funciona?Qual a vantagem de utilizar um rob√ī de criptomoedas?Bitsgap √© confi√°vel? O mercado de trading tem se tornado cada vez mais popular e as possibilidades de...

Hoje, às 13:13

Hacker News

Sketch of a Post-ORM
I’ve been writing a lot of database access code as of late. It’s frustrating that in 2023, my choices are still to either write all of the boilerplate by hand, or hand all database access over to some...

Hoje, às 13:11

Showmetech

14 chuveiros elétricos para o banho dos seus sonhos
√ćndice Chuveiro ou Ducha?Tipos de chuveiro el√©trico9 fatores importantes para considerar na hora de comprar chuveiros el√©tricosMelhores chuveiros el√©tricosDuo Shower LorenzettiFit HydraAcqua Storm Ultra...

Hoje, às 11:00

DEV

Learn about the difference between var, let, and const keywords in JavaScript and when to use them.
var, let, and const: What's the Difference in JavaScript? JavaScript is a dynamic and flexible language that allows you to declare variables in different ways. You can use var, let, or const keywords to...

Hoje, às 10:21