aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/api/canvas_api/tutorial/basic_usage
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/web/api/canvas_api/tutorial/basic_usage
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/uk/web/api/canvas_api/tutorial/basic_usage')
-rw-r--r--files/uk/web/api/canvas_api/tutorial/basic_usage/index.html152
1 files changed, 152 insertions, 0 deletions
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
+---
+<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}</div>
+
+<div class="summary">
+<p>Давайте почнемо цей урок з розгляду елемента  {{HTMLElement("canvas")}} {{Glossary("HTML")}} як такого. Наприкінці ви дізнаєтесь, як задати canvas 2D context та  зможете намалювати перший приклад в соєму браузері.</p>
+</div>
+
+<h2 id="Елемент_&lt;canvas>">Елемент <code>&lt;canvas&gt;</code></h2>
+
+<pre class="brush: html notranslate">&lt;canvas id="tutorial" width="150" height="150"&gt;&lt;/canvas&gt;
+</pre>
+
+<p>Елемент {{HTMLElement("canvas")}} схожий на елемент {{HTMLElement("img")}} , з єдиною видимою різницею - він не має атрибутів <code>src</code> та <code>alt</code> attributes. Дійсно, <code>&lt;canvas&gt;</code> має лише два атрибути, {{htmlattrxref("width", "canvas")}} та{{htmlattrxref("height", "canvas")}}. Обидва вони не є обов'язковими, та можуть бути задані за допомогою {{Glossary("DOM")}} <a href="/en-US/docs/Web/API/HTMLCanvasElement">в</a>ластивостей. Коли значення <code>width</code> та <code>height</code> не встановлені, canvas за замовчуванням буде <strong>300 пікселів </strong>шириною, та <strong>150 пікселів</strong> у висоту. Також можливо задати довільні розміри за допомогою  {{Glossary("CSS")}}, але під час ренедерингу зображення буде масштабуватися згідно з його розмірами: якщо задані в CSS параметри не відповідають початковому співвідношенню сторін canvas, воно буде викривленим. </p>
+
+<div class="note">
+<p><strong>Примітка:</strong> Якщо ваше зображення здається викривленимб спробуйте задати атрибути <code>width</code> and <code>height</code> атрибути в тегу <code>&lt;canvas&gt;</code> не використовуючи CSS.</p>
+</div>
+
+<p>Атрибут <a href="/en-US/docs/Web/HTML/Global_attributes/id"><code>id</code></a> не специфіцний для  <code>&lt;canvas&gt;, проте це один з </code><a href="/en-US/docs/Web/HTML/Global_attributes">global HTML attributes</a> які можна викростивувати для  HTML елементів (наприклад, <code><a href="/en-US/docs/Web/HTML/Global_attributes/class">class</a></code>). Використання <code>id</code> завжди є хорошим рішенням, тому що полегшує ідентифікацію елемента в скрипті. .</p>
+
+<p><code>&lt;canvas&gt;</code> може бути стилізований так само, як і будь-яке звичайне зображення ({{cssxref("margin")}}, {{cssxref("border")}}, {{cssxref("background")}}…). Ці правила, однак, не впливають на фактичний малюнок на canvas. Ми побачимо, як це робиться в спеціальній главі цього підручника. Якщо до canvas не застосовуються правила стилізації, воно за замовчуванням буде повністю прозорим.</p>
+
+<div id="section_2">
+<h3 id="Резервний_вміст">Резервний вміст</h3>
+
+<p><code>&lt;canvas&gt;</code> відрізняється від {{HTMLElement("img")}} тим, щоя як і для {{HTMLElement("video")}}, {{HTMLElement("audio")}}, або {{HTMLElement("picture")}} елементів, легко визначити деякий резервний вміст, котрий буде відображатися в старих браузерах, що не підтримують <code>&lt;canvas&gt;</code>, таких, як версії Internet Explorer до 9ї версії чи  текстових браузерах. Ви завжди повинні задавати резервний вміст, який буде відображатися в таких браузерах.</p>
+
+<p>Задати резервний вміст дуже просто, достатнь просто вставити альтернативний контент всередину елемента <code>&lt;canvas&gt;</code>. Браузери, які його не підтримують, проігноруюьб контейнер та відобразять альтернативний вміст замість нього. Браузери, які підтримують, пропустять вміст <code>&lt;canvas&gt;</code> і просто покажуть зображення нормально.</p>
+
+<p>наприклад, ми можемо задати текстовий опис вмісту  canvas чи використати статичне зображення динамічно створюваного контентуge of the dynamically rendered content. This can look something like this:</p>
+
+<pre class="brush: html notranslate">&lt;canvas id="stockGraph" width="150" height="150"&gt;
+ current stock price: $3.15 + 0.15
+&lt;/canvas&gt;
+
+&lt;canvas id="clock" width="150" height="150"&gt;
+ &lt;img src="images/clock.png" width="150" height="150" alt=""/&gt;
+&lt;/canvas&gt;
+</pre>
+
+<p>Рекомендація користувачу встановити інший браузер, що підтримує canvas,  не допомогає тим з них, хто не може взагалі прочтитати вміст canvas, наприклад. Використання резервного вмісту або додаткового DOM допомогає <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility">make the canvas more accessible</a><a href="/en-US/docs/">.</a></p>
+
+<h3 id="Обовязковий_тег_&lt;canvas>">Обов'язковий тег <code>&lt;/canvas&gt;</code> </h3>
+
+<p>Як наслідок способу надання резервного вмісту,  на відміну від елемента {{HTMLElement("img")}}, {{HTMLElement("canvas")}} <strong>вимагає </strong> закриваючого тега (<code>&lt;/canvas&gt;</code>). у випадку його відстусності, весь документ після  <code>&lt;/canvas&gt;</code> буде розглядатися як резервний вміст та не буде показаний.</p>
+
+<p>Якщо резервний вміст не потрібен, простий <code>&lt;canvas id="foo" ...&gt;&lt;/canvas&gt;</code> повністю сумісний з усіма браузерами, що підтримують canvas.</p>
+
+<h2 id="The_rendering_context">The rendering context</h2>
+
+<p>The {{HTMLElement("canvas")}} element creates a fixed-size drawing surface that exposes one or more <strong>rendering contexts</strong>, 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, <a href="/en-US/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL</a> uses a 3D context based on <a class="external" href="http://www.khronos.org/opengles/" rel="external" title="http://en.wikipedia.org/wiki/OpenGL_ES">OpenGL ES</a>.</p>
+
+<p>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. <code>getContext()</code> takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify <code>"2d"</code> to get a {{domxref("CanvasRenderingContext2D")}}.</p>
+
+<pre class="brush: js notranslate">var canvas = document.getElementById('tutorial');
+var ctx = canvas.getContext('2d');
+</pre>
+
+<p>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 <code>getContext()</code> method.</p>
+
+<div id="section_5">
+<h2 id="Checking_for_support">Checking for support</h2>
+
+<p>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 <code>getContext()</code> method. Our code snippet from above becomes something like this:</p>
+
+<pre class="brush: js notranslate">var canvas = document.getElementById('tutorial');
+
+if (canvas.getContext) {
+ var ctx = canvas.getContext('2d');
+ // drawing code here
+} else {
+ // canvas-unsupported code here
+}
+</pre>
+</div>
+</div>
+
+<h2 id="A_skeleton_template">A skeleton template</h2>
+
+<p>Here is a minimalistic template, which we'll be using as a starting point for later examples.</p>
+
+<div class="note">
+<p><strong>Note:</strong> it is not good practice to embed a script inside HTML. We do it here to keep the example concise.</p>
+</div>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"/&gt;
+ &lt;title&gt;Canvas tutorial&lt;/title&gt;
+ &lt;script type="text/javascript"&gt;
+ function draw() {
+ var canvas = document.getElementById('tutorial');
+ if (canvas.getContext) {
+ var ctx = canvas.getContext('2d');
+ }
+ }
+ &lt;/script&gt;
+ &lt;style type="text/css"&gt;
+ canvas { border: 1px solid black; }
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body onload="draw();"&gt;
+ &lt;canvas id="tutorial" width="150" height="150"&gt;&lt;/canvas&gt;
+ &lt;/body&gt;
+&lt;/html&gt;
+</pre>
+
+<p>The script includes a function called <code>draw()</code>, 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.</p>
+
+<p>Here is how a template would look in action. As shown here, it is initially blank.</p>
+
+<p>{{EmbedLiveSample("A_skeleton_template", 160, 160)}}</p>
+
+<h2 id="A_simple_example">A simple example</h2>
+
+<p>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.</p>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"/&gt;
+ &lt;script type="application/javascript"&gt;
+ 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);
+ }
+ }
+ &lt;/script&gt;
+ &lt;/head&gt;
+ &lt;body onload="draw();"&gt;
+ &lt;canvas id="canvas" width="150" height="150"&gt;&lt;/canvas&gt;
+ &lt;/body&gt;
+&lt;/html&gt;
+</pre>
+
+<p>This example looks like this:</p>
+
+<p>{{EmbedLiveSample("A_simple_example", 160, 160, "https://mdn.mozillademos.org/files/228/canvas_ex1.png")}}</p>
+
+<p>{{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}</p>