Canvas and JavaScript. Drawing shapes

Canvas and JavaScript. Drawing shapes

Tag canvas creates an area on HTML page, inside which you can draw different shapes and animate them using JavaScript.

Create a drawing area

We register a paired tag canvas with an identifier and specify the arbitrary sizes of our area in HTML и CSS… For further work with JavaScript code, that’s enough.


// HTML код

//CSS код
#draw {
    width: 600px;
    height: 300px;
}

The default tag is canvas does not appear on HTML page. For clarity, for educational purposes, I will add a background with a marked grid to the area. X и Y axes.

Canvas and JavaScript. Drawing shapes.

JavaScript code

В JavaScript there are several commands to work with canvas, but first we need to get the element itself by its ID.


let canvas = document.getElementById('draw');

Then we get its context. To do this, call the method getContext () and indicate that we will draw in the context 2d.


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

Draw a filled rectangle

To draw a rectangle, call the variable ctx method fillRect () and give it the initial coordinates X,Y (top left point), width and height.


ctx.fillRect(150, 75, 150, 150); // x, y, width, height

Canvas and JavaScript. Drawing shapes.

By default, the shape is drawn with a black fill. To change the fill color, use the command fillStyle ().


ctx.fillStyle = 'pink';

Canvas and JavaScript. Drawing shapes.

Erase a rectangle

Method clearRect () clears the canvas from the shape. To erase the current rectangle, another rectangle with the same dimensions is used.


ctx.clearRect(0, 0, 600, 300); //стирает canvas

Draw a rectangle with no fill

commands rest (), stroke (), fill () control the fill and stroke of a shape.


ctx.strokeStyle = "gray"; //цвет обводки
ctx.lineWidth = "10"; //толщина обводки
ctx.rect(150, 75, 225, 150);
ctx.stroke();
ctx.fillStyle = "pink"; //цвет заливки
ctx.fill();

Canvas and JavaScript. Drawing shapes.

Drawing a triangle

Method beginPath () begins a new path. Using the method moveTo () fix the starting point with coordinates X и Yand the method lineTo () draws lines.


ctx.beginPath();
ctx.moveTo(225,150);
ctx.lineTo(75,100);
ctx.lineTo(200,50);
ctx.fill();

Canvas and JavaScript. Drawing shapes.

Drawing a circle

The circle is drawn using the method arc ()to which the arguments are passed.


ctx.lineWidth = 5; // толщина линии
// x,y,radius,startAngle,endAngle,anticlockwise
ctx.arc(200,200,75,0, 2*Math.PI,true);
ctx.stroke();

  • x, y – coordinates of the center of the circle
  • radius – radius of the circle
  • starting angle – starting angle of the circle
  • endAngle – the end angle of a full circle corresponds to the angle 2PI.
  • anticlockwise – drawing direction, true(counterclock-wise), false(clockwise)
Canvas and JavaScript. Drawing shapes.

In this tutorial, we learned how to draw a filled rectangle, an erase rectangle, and an unfilled rectangle with custom fill and stroke controls. In addition, you now have an idea of ​​how to draw a triangle and a circle.

Previous article Next article

Copying of materials is allowed only with the indication of the author (Mikhail Rusakov) and an indexed direct link to the site (http://myrusakov.ru)!

Add to my friends VK: http://vk.com/myrusakov.
If you want to rate me and my work, then write it in my group: http://vk.com/rusakovmy.

If you do not want to miss new materials on the site,
then you can subscribe to updates: Subscribe to updates

If you still have any questions, or you have a desire to comment on this article, then you can leave your comment at the bottom of the page.

Recommend this article to your friends:

If you liked the site, then post a link to it (on your site, on the forum, in contact):

  1. Button:

    It looks like this: How to create your website

  2. Text link:

    It looks like this: How to create your website

  3. BB-code of the link for forums (for example, you can put it in the signature):

Related Posts

Russia has stepped up attacks and IPSO against Kharkov: ISW explained the enemy’s plan

According to analysts, the Russian Federation does not have the forces to capture the city. Russia puts pressure on Kharkov/ photo ua.depositphotos.com The Russian invaders have stepped…

St. George’s Day according to the new calendar: what the saint helps with, what not to do

On the feast of St. George the Victorious, one of the most famous Christian saints is remembered. When is the day of St. George the Victorious and…

How many drones were shot down at night: The Air Force spoke about the results of the hunt (video)

The enemies launched attack drones from the occupied Crimea and the territory of the Russian Federation. Sky defenders shot down 15 drones / photo 126 separate territorial…

Today is Psychologist’s Day 2024: beautiful wishes and bright cards

On Psychologist’s Day, April 23, do not forget to congratulate your close representatives of this profession. Psychologist Day 2024 / photo ua.depositphotos.com Every year on April 23,…

Respite from the rains: today it will be dry in Kyiv

In the capital on April 23 it will be cloudy with clearings. No precipitation is expected in Kyiv on April 23 / photo KSCA On Tuesday, April…

The occupiers are planning to penetrate deep into Ukrainian positions in the Donetsk region, – ISW

Over the next weeks, Russian troops will continue to receive tactical victories along the Berdich-Novokalinovo line. The Ukrainian Armed Forces will strengthen their capabilities, but they need…

Leave a Reply

Your email address will not be published. Required fields are marked *