Вы находитесь на странице: 1из 7

C2L1a

Что такое Canvas? Во-первых это элемент Html для создания графики. А еще это контейнер и при помощи
скриптов вы можете использовать это место для Рисования animation, игр, data visualization, photo manipulation, and
real-time video processing.
Для работы с canvas нужно поместить соответствующий тэг в тело html документа. В браузере ничего не
изменилось? Воспользуемся инспектором элементов. Canvas на своем месте. Просто пока невидимый. Обратите
внимание на размеры по умолчанию. Ширина 300 и высота 150 пикселей.
У нас есть возможность задать новому элементу идентификатор, и в дальнейшем использовать его, скажем
для  изменения стиля или обращения к элементу через скрипт. Воспользуемся css стилями и установим элементу
canvas черный фон. Использование атрибутов width и height – это один из способов установить размерами canvas.
Единицы измерения по умолчанию – пиксели. Вы так же можете использовать проценты. Но мы будем устанавливать
размеры другим способом, об этом чуть позже. Нам потребуются нулевые отступы. Давайте еще создадим
предупреждение, которое увидит пользователь, если его браузер не поддерживает canvas. И укажем ссылку на
внешний файл, со скриптом, где мы будем сегодня строить кое-что очень интересное. Итак, в нашем первом проекте
должно быть 2 фала – html, с ним мы уже закончили работу и JavaScript, к работе над которым мы приступаем.
Мы будем использовать строгий режим, и это поможет нам писать "secure" JavaScript.

Создадим объект с именем «C» сокращенное от «creative». И наполним его свойствами и методами, которые будут
выполнять анимацию нашего первого проекта. Итак, нам потребуются 2 свойства. Создадим метод инициализации.
Для работы сначала необходимо извлечь узел в DOM, представляющий ранее созданный в HTML элемент canvas. Мы
сделаем это с помощью метода getElementById(). Альтернативой может быть метод querySelector(), возвращающий
первый элемент документа соответствующий указанному в качестве параметра селектору. Теперь у нас есть
возможность установить размеры. Хотелось бы получить полноэкранный режим.
Теперь, когда у вас есть узел элемента, мы можем получить доступ к контексту рисования, используя getContext()
метод. Вот возможные варианты типов контекста. Мы пользовались самым первым 2d. Давайте посмотрим, что
собой представляет этот контекст. Вызовем инициализацию.

Перед вами объект с большим количеством свойств и методов. Мы будем изучать их в этом курсе, а сейчас
давайте попробуем что-нибудь простое. Например, метод fillRect() – он рисует залитый прямоугольник. Первые два
аргумента это координаты левого верхнего угла. Далее ширина и высота. Цвет заливки по умолчанию черный. И нам
нужно переопределить его, чтобы увидеть фигуру на черном фоне. Аналогичным образом Вы можете поработать с
обводкой. Давайте попробуем интерактивные возможности. Привяжем фигуру к положению курсора. Воспользуемся
методом addEventListener() для регистрации движения мыши на нашем canvas. B качестве координат верхнего левого
угла прямоугольника установим координаты курсора. В этих свойствах находятся горизонтальная и вертикальная
координата относительно всего документа. Для корректной работы внутри обработчика событий необходимо
использовать имя объекта для обращения к его свойствам.
Обратите внимание, что canvas сохраняет все нарисованные прямоугольники.
Хотелось бы стирать предыдущие состояния. Самое простое – это просто закрасить весь canvas черным
цветом с помощью уже известного Вам метода fillRect(). Давайте определим цвет заливки, используя систему HSLA.
Порядок аргументов соответствует аббревиатуре: hue, saturation, lightness and alpha channel. Мы будем много работать
с цветами в этом курсе, и позднее будем разбирать цветовые схемы более подробно. Эти цифры соответствуют
черному полностью непрозрачному цвету. Предыдущие состояния стираются, похоже, что мы двигаем один и тот же
прямоугольник. Давайте попробуем сильно уменьшить значение прозрачности. Теперь появился след от движения.

The  CanvasRenderingContext2D interface provides the 2D rendering context for the drawing surface of a <canvas> element.
getContext() on a <canvas>, supplying "2d" as the argument:
To get an object of this interface, call 

Первая строка скрипта извлекает узел в DOM, представляющий <canvas>элемент, путем вызова document.getElementById()метода. Когда у вас
есть узел элемента, вы можете получить доступ к контексту рисования, используя его getContext()метод.

Canvas — это элемент в HTML5, который предоставляет API-интерфейс

The CanvasRenderingContext2D is an object that is used to issue 2D drawing commands to a canvas.

Strict mode makes it easier to write "secure" JavaScript.

The Canvas API provides two drawing contexts: 2D and 3D

C2L1a_eng
What is Canvas? First, it's an Html element for creating graphics. It is also a container and with the help of scripts you
can use this place for Drawing, animation, games, data visualization, photo manipulation, and real-time video processing.
To work with canvas, you need to place the appropriate tag in the body of the html document. Has anything changed
in the browser? Let's use the element inspector. Canvas is in place. Just invisible for now. Pay attention to the default sizes.
Width 300 and height 150 pixels.
We have the ability to set an identifier for a new element, and later use it, say, to change the style or access the
element through a script. Let's use css styles and set the canvas element to a black background. Using the width and height
attributes is one way to set the dimensions of the canvas. The default units are pixels. You can also use percentages. But we
will set the dimensions in a different way, more on that later. We need zero padding. Let's also create a warning that will
appear if the browser does not support canvas. And we will indicate this link to an external file, with a script, where we will
build something very interesting today. So, in our first project there should be 2 files - html, we have already finished with it
and JavaScript, which we are starting to work on.
We will be using strict mode and this will help us write "secure" JavaScript.

Let's create an object named "C" short for "creative". And fill it with properties and methods that will perform the
animation of our first project. So we need 2 properties. Canvas and ctx, short for context.

Let's create an initialization method. To work, you first need to extract the node in the DOM that represents the
previously created canvas element in HTML. We will do this with the getElementById() method. An alternative would be the
querySelector() method, which returns the first element of the document that matches the selector specified as a parameter.
Let's set the dimensions. We want to get full screen mode.
We can now access the drawing context using the getContext() method. Here are the possible context types. We used
the very first "2d". Let's see what this context is. To do this, we call the initialization

Here is an object with a large number of properties and methods. We will study them in this course, but for now let's
try something simple. For example, the fillRect() method - it draws a filled rectangle. The first two arguments are the
coordinates of the upper left corner. Next is the width and height. Nothing appeared because the default fill color is black. And
we need to override it to see the shape on our black background. Similarly, you can work with the stroke. Let's try the
interactive features. Anchor the shape to the cursor position. Let's use the addEventListener() method to register mouse
movement on our canvas. As the coordinates of the upper left corner of the rectangle, set the coordinates of the cursor. These
properties contain the horizontal and vertical coordinates relative to the entire document. Note that canvas retains all drawn
rectangles.
I would like to erase previous states. The simplest is to fill the entire canvas with using the fillRect() method you
already know. Let's define the fill color using the HSLA system. The order of the arguments corresponds to the abbreviation:
hue, saturation, lightness and alpha channel. We'll be working a lot with colors in this course, and we'll cover color schemes in
more detail later. These numbers correspond to , a completely opaque color. The previous states are erased, it looks like we
are moving the same rectangle. Let's try to reduce the transparency value a lot. Now there is a trace of movement.
C2L1b
Fade эффект является следствием использования альфаканала при заливке Canvas. Это лишь один из
вариантов очистки. Взгляните на другие доступные способы, В этом курсе мы все их попробуем. Продолжим
знакомство с canvas и способами ее анимации и всегда помним о красивом коде (под раздвижечки 24.04).
Для построения красивых анимаций нам потребуются вычисления. В случае интерактивных анимаций исходными
данными для вычислений могут быть координаты курсора. Создадим отдельные свойства для их хранения и
обеспечения возможности использования за пределами созданного объекта. Запись этих свойств будем вести внутри
обработчика событий при движении мыши.
Добавим кое-что еще. Создадим отдельные свойства: количество объектов для анимации и массив цветов.
Теперь второй метод нашего объекта. Метод очень простой и он должен будет наполнять массив цветов. При
amt = 10, это будет десять цветов из цветового круга. Наполнение происходит за счет параметра цикла,
использованного для определения значений Hue. Метод будет использоваться при инициализации. Надо убедиться в
том, что массив наполнен. Давайте попробуем его использовать. Возьмем такой-же цикл и построим прямоугольник.
В качестве координат установим текущее положение курсора и смещение, вычисленное с помощью
тригонометрических формул. Сами формулы не очень важны, это просто пример, чтобы проверить массив цветов.
Квадраты залиты разными цветами. Цветовая палитра работает. Из этого можно сделать нечто потрясающее.
Цикл нам еще потребуется, остальное уберем.
Добавим еще один массив, он будет хранить наши объекты анимации. Наполнение массива будет
происходить в цикле с помощью метода push(). Каждый добавленный элемент в массив будет представлять собой
объект, экземпляр класса Sprite. Методы этого класса будут определять поведение наших объектов анимации.
Нам предстоит создать этот класс, а сейчас давайте запомним эту строчку и разберем ее позднее. Создадим
последний метод нашего объекта. Это движок нашей анимации. Каждый созданный объект анимации будет
обновляться в соответствии с методом update класса Sprite.
Движок построен на requestAnimationFrame(), он позволит осуществлять рекурсивный вызов исходного
метода через равные промежутки времени. Мы еще встретимся с этим методом в этом курсе, рассмотрим
особенности его использования. А сейчас добавим вызов в самом конце метода инициализации.

Методы очистки Canvas. Интерактивная привязка объектов анимации к курсору мыши. Присвоение объектам
цветов hsla. Сборка движка анимации на основе requestAnimationFrame.

fade effect. Provided with an alpha channel when filling the canvas. This is just one option for cleaning the Canvas .
Take a look at the other methods available. In this course, we will try them all. Let's continue our acquaintance with canvas
and ways to animate it, and always keep in mind the beautiful code (for sliders 24.04).
To build animations, we need calculations. In the case of interactive animations, the initial data for calculations can be
the cursor coordinates. Let's create separate properties for this. We will use these properties inside the event handler when the
mouse moves.
Let's add something else. Let's create separate properties: the number of objects for animation and an array of colors.
Now the second method of our object. The method is very simple and it will need to build an array of colors. With amt
= 10, this will be ten colors from the color wheel. The construction is done using the loop parameter used to determine the
Hue values. The method will be used during initialization. Make sure the array is full. Let's try to use it. Let's take the same
cycle and build a rectangle. As coordinates, we set the current position of the cursor and the offset calculated using
trigonometric formulas. The formulas themselves are not very important, it's just an example to test an array of colors. The
squares are filled with different colors. The color palette works. You can make something amazing out of this. I will show
you.
We still need a cycle, we will remove the rest.
Let's add another array, it will store our animation objects. The array will be filled in a loop using the push() method.
Each element added to the array will be an object, an instance of the Sprite class. The methods of this class will define the
behavior of our animation objects.
We have to create this class, but for now let's remember this line and analyze it later. The last method of the object
remains. This is our animation engine. Each animation object will be updated according to the update method of the Sprite
class.
The engine is built on the requestAnimationFrame() method, it will allow you to recursively call the original method
at regular intervals. And now let's add a call at the very end of the initialization method.

C2L1с
Класс - это шаблон для создания объектов. Так, здесь заканчивается наш объект.
Итак, объявляем класс. В его теле будет 2 метода. Первый имеет специальное название – конструктор. Он служит для
инициализации экземпляра класса. Второй метод будет определять их поведение. Начнем с конструктора.
Конструктор принимает один параметр – options
Взгляните на аргументы, которые использовались при создании экземпляра класса. Они станут параметрами
конструктора.
Итак, устанавливаем начальные значения. Местоположение. Текущее и предыдущее. За основу будет взято положение
курсора мыши. Ну а дальше мы будем изменять текущее положение в соответствии с расчетами. Единственный
размер. Мы будем работать с квадратами. Цвет. Смещения по соответствующим осям. Еще один дополнительный вид
сдвига. И последний параметр, это своего рода разброс. Об этом чуть позже.
Начнем работать с методом update(). Для начала построим квадрат в текущих координатах с заданным цветом.
Проверим. Хорошо. Теперь добавим для нашего объекта 2 свойства. Это массивы, для хранения продолжительностей
жизни и углов. Смотрите, что из этого выйдет. После создания очередного экземпляра класса при движении курсора
мыши мы добавим в массив жизней единицу, тем самым зафиксировав начало жизни нового экземпляра. В массив
углов мы добавим параметр цикла.
Давайте еще в 2 раза увеличим значение параметра альфаканала. Вернемся к методу update(). Мы будем рисовать
квадрат только в том случае, если время жизни не превышает 150 единиц. Соответственно, после каждой отрисовки
время увеличивается. В противном случае, помощью метода splice() мы будем удалять элементы с индексом i из
массива объектов анимации, массива углов и массива жизней. Т.о. объекты анимации будут создаваться, проживать
жизнь меньше условных 150 единиц, двигаться при этом в соответствии с методом обновления и удаляться.
Проверим.
Так хорошо, теперь нужен интересный алгоритм движения. И вся магия будет твориться здесь – это всего 6 строк
кода.
Только есть одна небольшая проблема. Формула движения выглядит вот так! Ну да – на первый взгляд
выглядит сложновато.
Чтобы понять сложную вещь надо разделить ее на много простых. Декомпозиция и работа с частями.
Взгляните на итоговый расчет координат для текущего квадрата. Это инкремент двух видов сдвига, второй с
ослабляющим множителем gravity. В этих формулах неизвестны dx и dy. Вычисляются они так. Некий сдвиг
умножается тригонометрическую периодическую функцию.
Угол в этой формуле известен, но мы будем его постепенно уменьшать в течение жизни объекта анимации. А
вот неизвестный shift вычислим по формуле похожей на теорему Пифагора, только вместо корня квадратного
используем 0.25. Чтобы это понять, с этим надо поиграть и попробовать модифицировать. А сейчас скорректируем
размеры квадрата, пусть они меняются в течение жизни. Так уже лучше, но я не вижу вращений у этих разноцветных
хвостов. Давайте увеличим угол вот здесь.
И обернем вызов в событие ‘load’, наступающее по окончании загрузки.
Здесь отличное поле для экспериментов. Поиграйте с коэффициентами в формулах, измените количество объектов
анимации. Попробуйте менять время жизни объектов анимации.
Если Вам понравился данный материал, я буду очень рад Вашим звездочкам.
А на а следующем уроке я познакомлю Вас c Web Audio API [Audio Visualizer] и мы будем строить визуализаторы
Вашей любимой музыки.

C2L1с_eng
A class is a template for creating objects. So, this is where our creative object ends.
Let's declare a class named Sprite . It will have 2 methods in its body. The first one has a special name - constructor. It is
required to initialize class instances. The second method will determine the behavior of these instances. Let's start with the
constructor. It takes one parameter - options.
Take a look at the arguments that were used when creating instances of the class. They will become constructor parameters.
So, we set the initial values. Location. current and previous. The position of the mouse cursor will be taken as the basis. Well,
then we will change the current position in accordance with the calculations. Figure length. We will work with squares. Color.
Offsets along the corresponding axes. Another additional type of shift. And the last parameter is something like scattering.
More on this later.
Now the update() method. First, let's build a square in the current coordinates with a given color. Let's check. Good. Now let's
add 2 properties to our creative object. These are arrays to store lifetimes and angles. See what comes of it. After creating the
next instance of the class, when moving the mouse cursor, we will add a unit to the array of lives, thereby fixing the beginning
of the life of a new instance. In the array of angles, we will add a loop parameter.
Let's increase the value of the alpha channel parameter. Back to the update() method. We will only draw a square if the
lifetime does not exceed 150 units. . Otherwise, using the splice() method, we will remove elements with index i from the
array of animation objects, the array of angles, and the array of lives. Thus, animation objects will be created, live less than
150 units, move according to the update method and be deleted. Let's check.
So good, now we need an interesting movement algorithm. And all the magic will happen here - it's only 6 lines of code.
There is only one small problem. The formula looks like this! Well, yes - at first glance it looks complicated.
To understand a complex thing, you need to divide it into many simple ones. Decomposition and working with parts. Let's do
that. Take a look at the final coordinate calculation for the current square. This is an increment of two types of shift, the
second with a weakening coefficient. In these formulas, dx and dy are unknown. They are calculated like this. A certain shift
is multiplied by a trigonometric periodic function.
The angle in this formula is known. And we will gradually reduce it during the life of the animation object. We calculate the
unknown shift using a formula similar to the Pythagorean theorem, but instead of the square root, we use the power of 0.25.
To understand this, you need to play with it and try to modify it. And now let's adjust the size of the square, let them change
throughout life. It looks more interesting now, but I don't see the rotations of those multi-colored tails. Let's increase the angle
here.
And we will wrap the call in the 'load' event, which occurs when the page is loaded.
This is a great field for experimentation. Play with coefficients in formulas, change the number of animation objects. Try to
change the time of life.
If you liked this material, I will be very happy with your stars.
And on this lesson came to an end, in the next lesson I will introduce you to the Web Audio API and we will build visualizers
for your favorite music.

Итак, для

Класс — тип, описывающий устройство объектов


класс – объект, способный порождать другие объекты – экземпляры
Класс (class) — это группа данных и методов (функций) для работы с этими данными

Класс - это шаблон для создания объектов

Вам также может понравиться