Canvas and JavaScript. Bee

Canvas and JavaScript. Bee

In this lesson, we will draw a bee using circles and animate it so that it flies. Animation creation in JavaScript consists of a repeating set of actions. The object is drawn first, then it is erased and redrawn elsewhere. This creates a sense of movement of the object.

Canvas and JavaScript. Bee.

Create a filled and stroked circle

To draw a bee, we need four circles, one of which will be filled with color (the body of the bee). Let’s create a variable circle and assign it a function that will create these circles. Let’s pass to the function the coordinates of the circle, the radius and the fill. Using the arc method, draw a full circle clockwise. Condition if-else will check if the argument matches fillCircle value true… If the condition is true, then the circle will be filled with color. Otherwise, we will end up with a circle with a stroke.


const circle = function (x, y, radius, fillCircle) {
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2, false)// метод arc создает окружность
    if (fillCircle) {// проверяем верно ли условие
        ctx.fill()//рисуем окружность с заливкой цветом
    } else {
        ctx.stroke()//иначе рисуем обводку
    }
};

Drawing a bee

Let’s create a function for drawing a bee drawBee… Using the function circle draw a set of circles with their own coordinates and radii.


function drawBee(x, y) {
    ctx.lineWidth = 2 // ширина контура
    ctx.strokeStyle = 'black' // цвет обводки
    ctx.fillStyle = 'gold' // цвет заливки

    circle(x, y, 8, true)
    circle(x, y, 8, false)
    circle(x - 5, y - 11, 5, false)
    circle(x + 5, y - 11, 5, false)
    circle(x - 2, y - 1, 2, false)
    circle(x + 2, y - 1, 2, false)
};

Bee position update

Let’s create a new function Updatewhich will update the coordinates of the bee’s position. Our bee will move randomly.


function update(coordinate) {
    let offset = Math.random() * 4 - 2 // формула случайного смещения
    coordinate += offset // изменение координат на величину смещения

    if (coordinate > 200){ // проверка нахождения пчелы в пределах холста
        coordinate = 200
    }
    if (coordinate < 0) {
        coordinate = 0
    }
    return coordinate // возвращение координаты
};

Animation start

Setting the starting coordinates x, y for the bee relative to the canvas. Every 30 seconds using the method setInterval run a function that clears the canvas, draws a bee with coordinates x, y and updates the coordinates of the bee’s position.


const canvas = document.getElementById('canvas') // получаем холст
const ctx= canvas.getContext('2d') // получаем контекст рисования

let x = 100
let y = 100

setInterval(function () {
    ctx.clearRect(0, 0, 200, 200) // очищение холста

    drawBee(x, y) // позиция пчелы
    x = update(x) // обновление значения x
    y = update(y) // обновление значения y

    ctx.strokeRect(0, 0, 200, 200) // обводка границ холста
}, 30)

The bee flies randomly across the screen within the canvas boundaries.

Take a look at an example at CodePen

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 *