aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/canvas_api/tutorial/advanced_animations
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/api/canvas_api/tutorial/advanced_animations
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/ru/web/api/canvas_api/tutorial/advanced_animations')
-rw-r--r--files/ru/web/api/canvas_api/tutorial/advanced_animations/index.html376
1 files changed, 376 insertions, 0 deletions
diff --git a/files/ru/web/api/canvas_api/tutorial/advanced_animations/index.html b/files/ru/web/api/canvas_api/tutorial/advanced_animations/index.html
new file mode 100644
index 0000000000..f9dc3f7a3e
--- /dev/null
+++ b/files/ru/web/api/canvas_api/tutorial/advanced_animations/index.html
@@ -0,0 +1,376 @@
+---
+title: Расширенные анимации
+slug: Web/API/Canvas_API/Tutorial/Advanced_animations
+translation_of: Web/API/Canvas_API/Tutorial/Advanced_animations
+---
+<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}</div>
+
+<div class="summary">
+<p><span class="notranslate">В предыдущей главе мы сделали несколько <a href="/ru/docs/Web/API/Canvas_API/Tutorial/Basic_animations">базовых анимаций</a> и узнали, как можно двигать вещи.</span> <span class="notranslate"> В этой части мы более подробно рассмотрим само движение и собираемся добавить некоторую физику, чтобы сделать наши анимации более продвинутыми.</span></p>
+</div>
+
+<h2 id="Рисование_мяча"><span class="notranslate">Рисование мяча</span></h2>
+
+<p><span class="notranslate">Мы собираемся использовать шар для наших анимационных исследований, поэтому давайте сначала нарисуем этот шар на </span><code> canvas</code><span class="notranslate">.</span> Нам нужен следующий код.</p>
+
+<pre class="brush: html">&lt;canvas id="canvas" width="600" height="300"&gt;&lt;/canvas&gt;
+</pre>
+
+<p><span class="notranslate">Как обычно, нам нужен контекст рисования.</span> Чтобы нарисовать шар, мы создадим объект <code>ball</code>, который содержит свойства и метод <code>draw()</code> , чтобы нарисовать его на <code>canvas</code>.</p>
+
+<pre class="brush: js">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+var ball = {
+ x: 100,
+ y: 100,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+ball.draw();</pre>
+
+<p><span class="notranslate">Здесь нет ничего особенного, шар на самом деле представляет собой простой круг и рисуется с помощью метода</span> {{domxref("CanvasRenderingContext2D.arc()", "arc()")}}.</p>
+
+<h2 id="Добавление_скорости"><span class="notranslate">Добавление скорости</span></h2>
+
+<p>Теперь, когда у нас есть шар, мы готовы добавить базовую анимацию, как мы узнали из последней <a href="/ru/docs/Web/API/Canvas_API/Tutorial/Basic_animations">главы</a> этого урока. <span class="notranslate">Опять же,</span> {{domxref("window.requestAnimationFrame()")}} <span class="notranslate">помогает нам контролировать анимацию.</span> <span class="notranslate">Мяч перемещается, добавляя вектор скорости в положение.</span> <span class="notranslate">Для каждого кадра мы также</span> {{domxref("CanvasRenderingContext2D.clearRect", "очищаем", "", 1)}} <span class="notranslate"> холст, чтобы удалить старые круги из предыдущих кадров.</span></p>
+
+<pre class="brush: js; highlight:[8,9,24,25]">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+ x: 100,
+ y: 100,
+ vx: 5,
+ vy: 2,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+function draw() {
+ ctx.clearRect(0,0, canvas.width, canvas.height);
+ ball.draw();
+ ball.x += ball.vx;
+ ball.y += ball.vy;
+ raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e) {
+ raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener('mouseout', function(e) {
+ window.cancelAnimationFrame(raf);
+});
+
+ball.draw();
+</pre>
+
+<h2 id="Границы"><span class="notranslate" style="background-color: #e6ecf9;">Границы</span></h2>
+
+<p><span class="notranslate">Без какого-либо граничного коллизионного тестирования наш мяч быстро выбегает из холста.</span> <span class="notranslate"> Нам нужно проверить, не находятся ли <code>x</code> и <code>y</code> положения шара вне размеров холста и не инвертируют направление векторов скорости.</span> <span class="notranslate"> Для этого мы добавим следующие проверки в метод <code>draw</code> :</span></p>
+
+<pre class="brush: js">if (ball.y + ball.vy &gt; canvas.height || ball.y + ball.vy &lt; 0) {
+  ball.vy = -ball.vy;
+}
+if (ball.x + ball.vx &gt; canvas.width || ball.x + ball.vx &lt; 0) {
+  ball.vx = -ball.vx;
+}</pre>
+
+<h3 id="Первое_демо"><span class="notranslate">Первое демо</span></h3>
+
+<p><span class="notranslate">Посмотрим, как он выглядит в действии.</span> <span class="notranslate"> Переместите мышь на холст, чтобы запустить анимацию.</span></p>
+
+<div class="hidden">
+<pre class="brush: html">&lt;canvas id="canvas" style="border: 1px solid" width="600" height="300"&gt;&lt;/canvas&gt;</pre>
+
+<pre class="brush: js">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+ x: 100,
+ y: 100,
+ vx: 5,
+ vy: 2,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+function draw() {
+ ctx.clearRect(0,0, canvas.width, canvas.height);
+ ball.draw();
+ ball.x += ball.vx;
+ ball.y += ball.vy;
+
+ if (ball.y + ball.vy &gt; canvas.height ||
+ ball.y + ball.vy &lt; 0) {
+ ball.vy = -ball.vy;
+ }
+ if (ball.x + ball.vx &gt; canvas.width ||
+ ball.x + ball.vx &lt; 0) {
+ ball.vx = -ball.vx;
+ }
+
+ raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e) {
+ raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener('mouseout', function(e) {
+ window.cancelAnimationFrame(raf);
+});
+
+ball.draw();</pre>
+</div>
+
+<p>{{EmbedLiveSample("First_demo", "610", "310")}}</p>
+
+<h2 id="Ускорение">Ускорение</h2>
+
+<p>Чтобы сделать движение более реальным, вы можете играть со скоростью, нпример так:</p>
+
+<pre class="brush: js">ball.vy *= .99;
+ball.vy += .25;</pre>
+
+<p><span class="notranslate">Это замедляет вертикальную скорость каждого кадра, так что мяч будет просто отскакивать от пола в конце.</span></p>
+
+<div class="hidden">
+<h6 id="Second_demo">Second demo</h6>
+
+<pre class="brush: html">&lt;canvas id="canvas" style="border: 1px solid" width="600" height="300"&gt;&lt;/canvas&gt;</pre>
+
+<pre class="brush: js">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+ x: 100,
+ y: 100,
+ vx: 5,
+ vy: 2,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+function draw() {
+ ctx.clearRect(0,0, canvas.width, canvas.height);
+ ball.draw();
+ ball.x += ball.vx;
+ ball.y += ball.vy;
+ ball.vy *= .99;
+ ball.vy += .25;
+
+ if (ball.y + ball.vy &gt; canvas.height ||
+ ball.y + ball.vy &lt; 0) {
+ ball.vy = -ball.vy;
+ }
+ if (ball.x + ball.vx &gt; canvas.width ||
+ ball.x + ball.vx &lt; 0) {
+ ball.vx = -ball.vx;
+ }
+
+ raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e) {
+ raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener('mouseout', function(e) {
+ window.cancelAnimationFrame(raf);
+});
+
+ball.draw();</pre>
+</div>
+
+<p>{{EmbedLiveSample("Second_demo", "610", "310")}}</p>
+
+<h2 id="Скользящий_эффект">Скользящий эффект</h2>
+
+<p>До сих пор мы использовали метод {{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}}, когда очищали предыдущий кадр. Если заменить этот метод на {{domxref("CanvasRenderingContext2D.fillRect", "fillRect")}} с полу-прозрачным стилем, можно легко создать эффект скольжения.</p>
+
+<pre class="brush: js">ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
+ctx.fillRect(0, 0, canvas.width, canvas.height);</pre>
+
+<div class="hidden">
+<h6 id="Third_demo">Third demo</h6>
+
+<pre class="brush: html">&lt;canvas id="canvas" style="border: 1px solid" width="600" height="300"&gt;&lt;/canvas&gt;</pre>
+
+<pre class="brush: js">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+ x: 100,
+ y: 100,
+ vx: 5,
+ vy: 2,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+function draw() {
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ball.draw();
+ ball.x += ball.vx;
+ ball.y += ball.vy;
+ ball.vy *= .99;
+ ball.vy += .25;
+
+ if (ball.y + ball.vy &gt; canvas.height ||
+ ball.y + ball.vy &lt; 0) {
+ ball.vy = -ball.vy;
+ }
+ if (ball.x + ball.vx &gt; canvas.width ||
+ ball.x + ball.vx &lt; 0) {
+ ball.vx = -ball.vx;
+ }
+
+ raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e) {
+ raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener('mouseout', function(e) {
+ window.cancelAnimationFrame(raf);
+});
+
+ball.draw();</pre>
+</div>
+
+<p>{{EmbedLiveSample("Third_demo", "610", "310")}}</p>
+
+<h2 id="Добавление_управления_мышью"><span class="notranslate" style="background-color: #e6ecf9;">Добавление управления мышью</span></h2>
+
+<p>Чтобы получить некоторый контроль над мячом, мы можем заставить его следовать за нашей мышью, например, с помощью события<span class="notranslate"> <code><a href="https://translate.googleusercontent.com/translate_c?depth=1&amp;hl=ru&amp;rurl=translate.google.com&amp;sl=en&amp;sp=nmt4&amp;tl=ru&amp;u=https://developer.mozilla.org/en-US/docs/Web/Reference/Events/mousemove&amp;usg=ALkJrhhcJqJN-yKD36pH8RkWQhb3uewyBA">mousemove</a></code> .</span> <span class="notranslate"> Событие <code><a href="https://translate.googleusercontent.com/translate_c?depth=1&amp;hl=ru&amp;rurl=translate.google.com&amp;sl=en&amp;sp=nmt4&amp;tl=ru&amp;u=https://developer.mozilla.org/en-US/docs/Web/Events/click&amp;usg=ALkJrhi9Rqodjh09zJQ7RSZkVNVqMZ5zhw">click</a></code></span> отпускает мяч и позволяет ему снова прыгать</p>
+
+<div class="hidden">
+<pre class="brush: html">&lt;canvas id="canvas" style="border: 1px solid" width="600" height="300"&gt;&lt;/canvas&gt;</pre>
+</div>
+
+<pre class="brush: js">var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+var running = false;
+
+var ball = {
+ x: 100,
+ y: 100,
+ vx: 5,
+ vy: 1,
+ radius: 25,
+ color: 'blue',
+ draw: function() {
+ ctx.beginPath();
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+ ctx.closePath();
+ ctx.fillStyle = this.color;
+ ctx.fill();
+ }
+};
+
+function clear() {
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
+ ctx.fillRect(0,0,canvas.width,canvas.height);
+}
+
+function draw() {
+ clear();
+ ball.draw();
+ ball.x += ball.vx;
+ ball.y += ball.vy;
+
+ if (ball.y + ball.vy &gt; canvas.height || ball.y + ball.vy &lt; 0) {
+ ball.vy = -ball.vy;
+ }
+ if (ball.x + ball.vx &gt; canvas.width || ball.x + ball.vx &lt; 0) {
+ ball.vx = -ball.vx;
+ }
+
+ raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mousemove', function(e) {
+ if (!running) {
+ clear();
+ ball.x = e.clientX;
+ ball.y = e.clientY;
+ ball.draw();
+ }
+});
+
+canvas.addEventListener('click', function(e) {
+ if (!running) {
+ raf = window.requestAnimationFrame(draw);
+ running = true;
+ }
+});
+
+canvas.addEventListener('mouseout', function(e) {
+ window.cancelAnimationFrame(raf);
+ running = false;
+});
+
+ball.draw();
+</pre>
+
+<p><span class="notranslate">Переместите шар с помощью мыши и отпустите его одним щелчком.</span></p>
+
+<p>{{EmbedLiveSample("Adding_mouse_control", "610", "310")}}</p>
+
+<h2 id="Breakout(арканоид)">Breakout(арканоид)</h2>
+
+<p>В этой короткой главе описаны некоторые приемы создания продвинутой анимации.  Как насчет того, что бы добавить доску, кирпичи и превратить это демо в игру Breakout(в Росси более известный клон этой игры - арканоид)? Посетите <a href="/en-US/docs/Games">Game development</a> чтобы узнать больше об играх.</p>
+
+<h2 id="Смотрите_так_же">Смотрите так же</h2>
+
+<ul>
+ <li>{{domxref("window.requestAnimationFrame()")}}</li>
+ <li><a href="/en-US/docs/Games/Techniques/Efficient_animation_for_web_games">Efficient animation for web games</a></li>
+</ul>
+
+<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}</p>