From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../api/canvas_api/tutorial/basic_usage/index.html | 152 +++++++++++++++++++++ files/uk/web/api/canvas_api/tutorial/index.html | 63 +++++++++ .../index.html" | 108 +++++++++++++++ 3 files changed, 323 insertions(+) create mode 100644 files/uk/web/api/canvas_api/tutorial/basic_usage/index.html create mode 100644 files/uk/web/api/canvas_api/tutorial/index.html create mode 100644 "files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" (limited to 'files/uk/web/api/canvas_api/tutorial') diff --git a/files/uk/web/api/canvas_api/tutorial/basic_usage/index.html b/files/uk/web/api/canvas_api/tutorial/basic_usage/index.html new file mode 100644 index 0000000000..e57e9fe4a0 --- /dev/null +++ b/files/uk/web/api/canvas_api/tutorial/basic_usage/index.html @@ -0,0 +1,152 @@ +--- +title: Базове використання canvas +slug: Web/API/Canvas_API/Tutorial/Basic_usage +translation_of: Web/API/Canvas_API/Tutorial/Basic_usage +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}
+ +
+

Давайте почнемо цей урок з розгляду елемента  {{HTMLElement("canvas")}} {{Glossary("HTML")}} як такого. Наприкінці ви дізнаєтесь, як задати canvas 2D context та  зможете намалювати перший приклад в соєму браузері.

+
+ +

Елемент <canvas>

+ +
<canvas id="tutorial" width="150" height="150"></canvas>
+
+ +

Елемент {{HTMLElement("canvas")}} схожий на елемент {{HTMLElement("img")}} , з єдиною видимою різницею - він не має атрибутів src та alt attributes. Дійсно, <canvas> має лише два атрибути, {{htmlattrxref("width", "canvas")}} та{{htmlattrxref("height", "canvas")}}. Обидва вони не є обов'язковими, та можуть бути задані за допомогою {{Glossary("DOM")}} властивостей. Коли значення width та height не встановлені, canvas за замовчуванням буде 300 пікселів шириною, та 150 пікселів у висоту. Також можливо задати довільні розміри за допомогою  {{Glossary("CSS")}}, але під час ренедерингу зображення буде масштабуватися згідно з його розмірами: якщо задані в CSS параметри не відповідають початковому співвідношенню сторін canvas, воно буде викривленим. 

+ +
+

Примітка: Якщо ваше зображення здається викривленимб спробуйте задати атрибути width and height атрибути в тегу <canvas> не використовуючи CSS.

+
+ +

Атрибут id не специфіцний для  <canvas>, проте це один з global HTML attributes які можна викростивувати для  HTML елементів (наприклад, class). Використання id завжди є хорошим рішенням, тому що полегшує ідентифікацію елемента в скрипті. .

+ +

<canvas> може бути стилізований так само, як і будь-яке звичайне зображення ({{cssxref("margin")}}, {{cssxref("border")}}, {{cssxref("background")}}…). Ці правила, однак, не впливають на фактичний малюнок на canvas. Ми побачимо, як це робиться в спеціальній главі цього підручника. Якщо до canvas не застосовуються правила стилізації, воно за замовчуванням буде повністю прозорим.

+ +
+

Резервний вміст

+ +

<canvas> відрізняється від {{HTMLElement("img")}} тим, щоя як і для {{HTMLElement("video")}}, {{HTMLElement("audio")}}, або {{HTMLElement("picture")}} елементів, легко визначити деякий резервний вміст, котрий буде відображатися в старих браузерах, що не підтримують <canvas>, таких, як версії Internet Explorer до 9ї версії чи  текстових браузерах. Ви завжди повинні задавати резервний вміст, який буде відображатися в таких браузерах.

+ +

Задати резервний вміст дуже просто, достатнь просто вставити альтернативний контент всередину елемента <canvas>. Браузери, які його не підтримують, проігноруюьб контейнер та відобразять альтернативний вміст замість нього. Браузери, які підтримують, пропустять вміст <canvas> і просто покажуть зображення нормально.

+ +

наприклад, ми можемо задати текстовий опис вмісту  canvas чи використати статичне зображення динамічно створюваного контентуge of the dynamically rendered content. This can look something like this:

+ +
<canvas id="stockGraph" width="150" height="150">
+  current stock price: $3.15 + 0.15
+</canvas>
+
+<canvas id="clock" width="150" height="150">
+  <img src="images/clock.png" width="150" height="150" alt=""/>
+</canvas>
+
+ +

Рекомендація користувачу встановити інший браузер, що підтримує canvas,  не допомогає тим з них, хто не може взагалі прочтитати вміст canvas, наприклад. Використання резервного вмісту або додаткового DOM допомогає make the canvas more accessible.

+ +

Обов'язковий тег </canvas> 

+ +

Як наслідок способу надання резервного вмісту,  на відміну від елемента {{HTMLElement("img")}}, {{HTMLElement("canvas")}} вимагає  закриваючого тега (</canvas>). у випадку його відстусності, весь документ після  </canvas> буде розглядатися як резервний вміст та не буде показаний.

+ +

Якщо резервний вміст не потрібен, простий <canvas id="foo" ...></canvas> повністю сумісний з усіма браузерами, що підтримують canvas.

+ +

The rendering context

+ +

The {{HTMLElement("canvas")}} element creates a fixed-size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. In this tutorial, we focus on the 2D rendering context. Other contexts may provide different types of rendering; for example, WebGL uses a 3D context based on OpenGL ES.

+ +

The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it. The {{HTMLElement("canvas")}} element has a method called {{domxref("HTMLCanvasElement.getContext", "getContext()")}}, used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a {{domxref("CanvasRenderingContext2D")}}.

+ +
var canvas = document.getElementById('tutorial');
+var ctx = canvas.getContext('2d');
+
+ +

The first line in the script retrieves the node in the DOM representing the {{HTMLElement("canvas")}} element by calling the {{domxref("document.getElementById()")}} method. Once you have the element node, you can access the drawing context using its getContext() method.

+ +
+

Checking for support

+ +

The fallback content is displayed in browsers which do not support {{HTMLElement("canvas")}}. Scripts can also check for support programmatically by simply testing for the presence of the getContext() method. Our code snippet from above becomes something like this:

+ +
var canvas = document.getElementById('tutorial');
+
+if (canvas.getContext) {
+  var ctx = canvas.getContext('2d');
+  // drawing code here
+} else {
+  // canvas-unsupported code here
+}
+
+
+
+ +

A skeleton template

+ +

Here is a minimalistic template, which we'll be using as a starting point for later examples.

+ +
+

Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise.

+
+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>Canvas tutorial</title>
+    <script type="text/javascript">
+      function draw() {
+        var canvas = document.getElementById('tutorial');
+        if (canvas.getContext) {
+          var ctx = canvas.getContext('2d');
+        }
+      }
+    </script>
+    <style type="text/css">
+      canvas { border: 1px solid black; }
+    </style>
+  </head>
+  <body onload="draw();">
+    <canvas id="tutorial" width="150" height="150"></canvas>
+  </body>
+</html>
+
+ +

The script includes a function called draw(), which is executed once the page finishes loading; this is done by listening for the {{event("load")}} event on the document. This function, or one like it, could also be called using {{domxref("WindowTimers.setTimeout", "window.setTimeout()")}}, {{domxref("WindowTimers.setInterval", "window.setInterval()")}}, or any other event handler, as long as the page has been loaded first.

+ +

Here is how a template would look in action. As shown here, it is initially blank.

+ +

{{EmbedLiveSample("A_skeleton_template", 160, 160)}}

+ +

A simple example

+ +

To begin, let's take a look at a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll explore how this works in more detail in later examples.

+ +
<!DOCTYPE html>
+<html>
+ <head>
+  <meta charset="utf-8"/>
+  <script type="application/javascript">
+    function draw() {
+      var canvas = document.getElementById('canvas');
+      if (canvas.getContext) {
+        var ctx = canvas.getContext('2d');
+
+        ctx.fillStyle = 'rgb(200, 0, 0)';
+        ctx.fillRect(10, 10, 50, 50);
+
+        ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
+        ctx.fillRect(30, 30, 50, 50);
+      }
+    }
+  </script>
+ </head>
+ <body onload="draw();">
+   <canvas id="canvas" width="150" height="150"></canvas>
+ </body>
+</html>
+
+ +

This example looks like this:

+ +

{{EmbedLiveSample("A_simple_example", 160, 160, "https://mdn.mozillademos.org/files/228/canvas_ex1.png")}}

+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}

diff --git a/files/uk/web/api/canvas_api/tutorial/index.html b/files/uk/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..f712d8ed88 --- /dev/null +++ b/files/uk/web/api/canvas_api/tutorial/index.html @@ -0,0 +1,63 @@ +--- +title: Canvas tutorial +slug: Web/API/Canvas_API/Tutorial +tags: + - Canvas + - Graphics + - Guide + - HTML + - HTML5 + - Intermediate + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{CanvasSidebar}}
+ +

+ +
+

<canvas> is an HTML element which can be used to draw graphics using scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial.

+
+ +

This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with canvas and will provide code snippets that may get you started in building your own content.

+ +

First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it.

+ +

Before you start

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

In this tutorial

+ + + +

See also

+ + + +

A note to contributors

+ +

Due to an unfortunate technical error that occurred the week of June 17, 2013, we lost the history of this tutorial, including attributions to all past contributors to its content. We apologize for this, and hope you'll forgive this unfortunate mishap.

+ +
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git "a/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" "b/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" new file mode 100644 index 0000000000..cb7b8b615b --- /dev/null +++ "b/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" @@ -0,0 +1,108 @@ +--- +title: Чутливі ділянки та доступність +slug: Web/API/Canvas_API/Tutorial/Чутливі_ділянки_та_доступність +tags: + - Canvas + - Графіка + - Полотно + - Підручник +translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility +--- +
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
+ +
Власне HTML-елемент {{HTMLElement("canvas")}} являє собою лише множину кольорових точок і не містить жодних відомостей про намальовані об'єкти. Вміст полотна жодним чином не розкривається інструментам доступності, як це передбачено для семантичного HTML. Тож загалом, слід уникати використання полотен в застосунках або сайтах, від яких вимагається підтримка доступності. Проте наведені нижче настанови допоможуть все ж дещо уприступнити вміст полотен.
+ +

Запасний вміст

+ +

Вміст між тегами <canvas> … </canvas> може відігравати роль запасного варіанту для тих {{glossary("Browser", "переглядачів")}}, що не мають підтримки полотен. Він також вельми корисний тоді, коли користувач потребує допоміжних засобів (як-от екранний диктор), які можуть читати дерево DOM всередині. Чудовий приклад з html5accessibility.com показує, як це можна здійснити:

+ +
<canvas>
+  <h2>Shapes</h2>
+  <p>A rectangle with a black border.
+   In the background is a pink circle.
+   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
+   Partially overlaying the circle is a green
+   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
+   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
+   both of which are semi-opaque, so the full circle can be seen underneath.</p>
+</canvas> 
+ +

Перегляньте відео від Стіва Фолкнера про те, як екранний диктор NVDA читає цей приклад.

+ +

Правила ARIA

+ +

Accessible Rich Internet Applications (ARIA) визначає способи того, як зробити веб-застосунки та вміст доступнішими для людей з певними вадами. Можна вжити ARIA-атрибути для описання поведінки й призначення HTML-елемента полотна:

+ +
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
+
+ +

Дивіться ARIA та Використання ARIA, щоб дізнатись більше.

+ +

Чутливі ділянки

+ +

Однією з поширених задач є з'ясування того, чи належать координати миші до певної ділянки на полотні. Відповідний API уможливлює створення певних чутливих ділянок на полотні та дає інші можливості розкрити взаємодіяльний вміст полотна інструментам доступності. Він дозволяє полегшити виявлення влучень (належності координат миші певній ділянці) та доправити відповідні події до елементів DOM. Цей API має такі три методи (досі лишаються дослідними в сучасних переглядачах, тож перевіряйте таблиці сумісності):

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
Створює чутливу ділянку на полотні.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
Видаляє з полотна чутливу ділянку із зазначеним id .
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
Видаляє з полотна всі чутливі ділянки.
+
+ +

Створюючи новий контур з допомогою {{domxref("CanvasRenderingContext2D.beginPath()")}} можна перетворити його на чутливу ділянку, а тоді, перевіряючи значення властивості {{domxref("MouseEvent.region")}}, з'ясовувати, чи влучає миша у вказану область:

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: 'circle'});
+
+canvas.addEventListener('mousemove', function(event) {
+  if (event.region) {
+    console.log('Влучив у ділянку: ' + event.region);  // Влучив у ділянку: circle
+  }
+});
+
+ +

Крім того, метод addHitRegion() може також приймати параметр control, що вказує елемент (має бути нащадком елемента canvas), до якого доправлятимуться події:

+ +
ctx.addHitRegion({control: element});
+ +

Наприклад, це може стати в нагоді для доправлення подій до елементів {{HTMLElement("input")}}.

+ +

Облямівки фокуса

+ +

Для роботи з клавіатури, облямівки фокуса є зручними індикаторами, що полегшують пересування сторінкою. Щоб намалювати облямівку фокуса навколо малюнка (контура) на полотні, можна скористатися методом drawFocusIfNeeded().

+ +
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
+
Якщо відповідний елемент перебуває у фокусі, цей метод намалює облямівку навколо контура.
+
+ +

Крім того, можна використати метод scrollPathIntoView(), щоб зробити елемент видимим на екрані, якщо він перебуває у фокусі, наприклад.

+ +
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
+
Гортає поточний чи вказаний контур до видимої області.
+
+ +

Див. також

+ + + +
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
-- cgit v1.2.3-54-g00ecf