Canvas and JavaScript. Animation

Canvas and JavaScript. Animation

What is great is that on Canvas you can not only draw, but also animate objects. To do this, have JavaScript there is a complete set of tools. You will learn how to make drawn in Canvas geometric shapes, move. The essence of animation is to clean up Canvas and drawing the new position of the shape. To do this, you need to create a function and call it at a specified time interval.

Create a drawing area


// Создание холста

// CSS стили
#canvas {
    width: 600px;
    height: 300px;
    margin: 40px;
    background-image: url(grid.png);
}

Drawing a square

Let’s add X a coordinate with a value of 75 to a variable positionXas the square will move horizontally.


let canvas = document.getElementById('canvas'); // получение холста в документе
let ctx = canvas.getContext('2d'); // получение контекста рисования
let positionX = 75; // начальная позиция X координаты

ctx.beginPath();
ctx.fillStyle = "pink"; // цвет заливки
ctx.rect(positionX, 75, 75, 75); // x, y, width, height
ctx.fill();

Animation of the movement of a square

Method setInterval takes two attributes: a function and a specified time interval. The function clears the canvas from the current position of the square and draws a new square each time, increasing the value of the variable positionX per unit. When the position reaches the canvas width value of 600 pixels, that is, the square is out of bounds canvas, then the initial value of the square’s position is set to 75. The square returns to its original position and the animation starts over. Thus, the function will run every 60 milliseconds. The shorter the time interval, the faster the figure moves.

Canvas and JavaScript. Animation.


let canvas = document.getElementById('canvas'); // получение холста в документе
let ctx = canvas.getContext('2d'); // получение контекста рисования
let positionX = 75; // начальная позиция X координаты

setInterval (function () {
    ctx.beginPath ();
    ctx.clearRect (0,0,600,300); // clear the canvas
    ctx.fillStyle = “pink”; // fill color
    ctx.rect (positionX, 75, 75, 75); // x, y, width, height
    ctx.fill ();
    positionX ++; // change position
    if (positionX> 600) {
        positionX = 75;
    }
}, 60); // run every 60 milliseconds

Look at CodePenas the square slowly moves to the right and when it reaches the right border of the drawing area, it returns to its original position.

If you do not clear the canvas, then the squares will begin to play and fill the entire trajectory of movement.

Canvas and JavaScript. Animation.

Animation of an enlargement of a square

Canvas and JavaScript. Animation.

Let’s add to the variable size the initial width and height of the square, and instead of the width and height, we will specify this variable in the command parameters rest… Then we will increase the size of the variable value by one size ++… When the size of the square reaches 225 pixels, the square will stop enlarging, the canvas will be cleared clearRect and we will see a small square again.


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

setInterval(function() {
    ctx.beginPath();
    ctx.clearRect(0,0,600,300); // очистка холста
    ctx.fillStyle = "pink"; // цвет заливки
    ctx.rect(75, 75, size, size); // x, y, width, height
    ctx.fill();
    size++; // увеличение размера
    if(size > 225) {
        size = 75;
    }
},60); // запуск каждые 60 миллисекунд

Look at CodePenas the square slowly increases in size and reaches the boundaries of the drawing area, returns to its original size

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

Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company

“Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company” In Dubai, one of the most dynamically developing regions in the world, the real estate…

In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident, – media

The guy crashed into a roadside pole at high speed. In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident / illustrative…

NATO saw no signs that the Russian Federation was planning an attack on one of the Alliance countries

Bauer recalled that according to Article 3 of the NATO treaty, every country must be able to defend itself. Rob Bauer commented on concerns that Russia is…

The Russian Federation has modernized the Kh-101 missile, doubling its warhead, analysts

The installation of an additional warhead in addition to the conventional high-explosive fragmentation one occurred due to a reduction in the size of the fuel tank. The…

Four people killed by storm in European holiday destinations

The deaths come amid warnings of high winds and rain thanks to Storm Nelson. Rescuers discovered bodies in two separate incidents / photo ua.depositphotos.com Four people, including…

Egg baba: a centuries-old recipe of 24 yolks for Catholic Easter

They like to put it in the Easter basket in Poland. However, many countries have their own variations of “bab”. The woman’s original recipe is associated with…

Leave a Reply

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