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.
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.
If you liked the site, then post a link to it (on your site, on the forum, in contact):
-
Button:
It looks like this:
-
Text link:
It looks like this: How to create your website
- BB-code of the link for forums (for example, you can put it in the signature):