Artykuł marzec 2018
W trakcie tej lekcji nauczysz się: Definiować element canvas, atrybuty szerokości i wysokości. Publikować obraz na stronie internetowej.- URL:
- http://canvas-2d.blogspot.com/2018/04/canvas.html
- Autor:
- Radosław Kowaluk
Copyright © 2018 Obowiązują zasady odpowiedzialności karnej, znaków towarowych i zasad W3C.
Wstęp
Elementcanvas
jest znacznikiem HTML5, który tworzy obraz na stronie internetowej na podstawie kodu JavaScript.
Element canvas
i script
Domyślnie element canvas
tworzy przezroczysty obraz PNG, o wymiarach 300 x 150 (pikseli). Układ współrzędnych jest taki jak w każdej grafice.Zanalizujmy aktywnie przykłady.
Domyślny element
Przetestuj przykład zmieniając kod w lewym prostokącie.
Na początku skryptu obowiązkowo deklarujemy zmienną (canvas
.Przetestuj przykład zmieniając kod w lewym prostokącie.
W przykładzie dodano pomocnicze obramowanie elementu
canvas
za pomocą atrybutu style
i reguły CSS border
. Zawartością może być tekst alternatywny, który zostanie wyświetlony jeżeli przeglądarka nie będzie mogła zaprezentować elementu canvas
.
var nazwa_zmiennej
) i za pomocą metody getContext("2d")
przypisujemy jej wartość (operator przypisania =
). Wielkość liter ma znaczenie. Nazwy zmiennych muszą zaczynać się od litery, znaków $ i _.
W przykładzie dodano metodę
Zmień nazwę zmiennej.
Innym sposobem jest zapisanie kodu w osobnym pliku (z rozszerzeniem .js) i określenie jego adresu w atrybucie getContext("2d")
w elemencie script
.Zmień nazwę zmiennej.
Element
script
może posiadać atrybut type
z wartością "text/javascript"
, który w HTML 5 można pominąć, . Popularnym sposobem odwołania się do elementu canvas
o identyfikatorze id="c1"
jest metoda obiektu document
document.getElementById("c1")
, którą będziemy pomijać, . Poszczególne linie kodu możemy zakończyć średnikiem ;
.
src
.Podsumowując, możemy przyjąć następujące definicje.
canvas
- Element HTML, zawierający opcjonalny alternatywny tekst i tworzący obraz, którego zawartość jest zdefiniowana skryptem. Może być definiowany z atrybutami
width
iheight
.Więcej
Interfejs elementucanvas
width = 0
height = 0
captureStream = function captureStream() { [native code] }
getContext = function getContext() { [native code] }
toBlob = function toBlob() { [native code] }
toDataURL = function toDataURL() { [native code] }
transferControlToOffscreen = function transferControlToOffscreen() { [native code] }
title =
lang =
translate = true
dir =
hidden = false
inert = false
accessKey =
draggable = false
spellcheck = true
autocapitalize =
editContext = null
contentEditable = inherit
enterKeyHint =
isContentEditable = false
inputMode =
virtualKeyboardPolicy =
offsetParent = [object HTMLBodyElement]
offsetTop = 1896
offsetLeft = 376
offsetWidth = 0
offsetHeight = 0
popover = null
innerText =
outerText =
writingSuggestions = true
onbeforexrselect = null
onabort = null
onbeforeinput = null
onbeforematch = null
onbeforetoggle = null
onblur = null
oncancel = null
oncanplay = null
oncanplaythrough = null
onchange = null
onclick = null
onclose = null
oncontentvisibilityautostatechange = null
oncontextlost = null
oncontextmenu = null
oncontextrestored = null
oncuechange = null
ondblclick = null
ondrag = null
ondragend = null
ondragenter = null
ondragleave = null
ondragover = null
ondragstart = null
ondrop = null
ondurationchange = null
onemptied = null
onended = null
onerror = null
onfocus = null
onformdata = null
oninput = null
oninvalid = null
onkeydown = null
onkeypress = null
onkeyup = null
onload = null
onloadeddata = null
onloadedmetadata = null
onloadstart = null
onmousedown = null
onmouseenter = null
onmouseleave = null
onmousemove = null
onmouseout = null
onmouseover = null
onmouseup = null
onmousewheel = null
onpause = null
onplay = null
onplaying = null
onprogress = null
onratechange = null
onreset = null
onresize = null
onscroll = null
onsecuritypolicyviolation = null
onseeked = null
onseeking = null
onselect = null
onslotchange = null
onstalled = null
onsubmit = null
onsuspend = null
ontimeupdate = null
ontoggle = null
onvolumechange = null
onwaiting = null
onwebkitanimationend = null
onwebkitanimationiteration = null
onwebkitanimationstart = null
onwebkittransitionend = null
onwheel = null
onauxclick = null
ongotpointercapture = null
onlostpointercapture = null
onpointerdown = null
onpointermove = null
onpointerrawupdate = null
onpointerup = null
onpointercancel = null
onpointerover = null
onpointerout = null
onpointerenter = null
onpointerleave = null
onselectstart = null
onselectionchange = null
onanimationend = null
onanimationiteration = null
onanimationstart = null
ontransitionrun = null
ontransitionstart = null
ontransitionend = null
ontransitioncancel = null
oncopy = null
oncut = null
onpaste = null
dataset = [object DOMStringMap]
nonce =
autofocus = false
tabIndex = -1
style = [object CSSStyleDeclaration]
attributeStyleMap = [object StylePropertyMap]
attachInternals = function attachInternals() { [native code] }
blur = function blur() { [native code] }
click = function click() { [native code] }
focus = function focus() { [native code] }
hidePopover = function hidePopover() { [native code] }
showPopover = function showPopover() { [native code] }
togglePopover = function togglePopover() { [native code] }
onscrollend = null
onscrollsnapchange = null
onscrollsnapchanging = null
namespaceURI = http://www.w3.org/1999/xhtml
prefix = null
localName = canvas
tagName = CANVAS
id = c1
className =
classList =
slot =
attributes = [object NamedNodeMap]
shadowRoot = null
part =
assignedSlot = null
innerHTML =
outerHTML =
scrollTop = undefined
scrollLeft = undefined
scrollWidth = undefined
scrollHeight = undefined
clientTop = undefined
clientLeft = undefined
clientWidth = undefined
clientHeight = undefined
onbeforecopy = undefined
onbeforecut = undefined
onbeforepaste = undefined
onsearch = undefined
elementTiming = undefined
onfullscreenchange = undefined
onfullscreenerror = undefined
onwebkitfullscreenchange = undefined
onwebkitfullscreenerror = undefined
role = undefined
ariaAtomic = undefined
ariaAutoComplete = undefined
ariaBusy = undefined
ariaBrailleLabel = undefined
ariaBrailleRoleDescription = undefined
ariaChecked = undefined
ariaColCount = undefined
ariaColIndex = undefined
ariaColSpan = undefined
ariaCurrent = undefined
ariaDescription = undefined
ariaDisabled = undefined
ariaExpanded = undefined
ariaHasPopup = undefined
ariaHidden = undefined
ariaInvalid = undefined
ariaKeyShortcuts = undefined
ariaLabel = undefined
ariaLevel = undefined
ariaLive = undefined
ariaModal = undefined
ariaMultiLine = undefined
ariaMultiSelectable = undefined
ariaOrientation = undefined
ariaPlaceholder = undefined
ariaPosInSet = undefined
ariaPressed = undefined
ariaReadOnly = undefined
ariaRelevant = undefined
ariaRequired = undefined
ariaRoleDescription = undefined
ariaRowCount = undefined
ariaRowIndex = undefined
ariaRowSpan = undefined
ariaSelected = undefined
ariaSetSize = undefined
ariaSort = undefined
ariaValueMax = undefined
ariaValueMin = undefined
ariaValueNow = undefined
ariaValueText = undefined
children = undefined
firstElementChild = undefined
lastElementChild = undefined
childElementCount = undefined
previousElementSibling = undefined
nextElementSibling = undefined
after = undefined
animate = undefined
append = undefined
attachShadow = undefined
before = undefined
checkVisibility = undefined
closest = undefined
computedStyleMap = undefined
getAnimations = undefined
getAttribute = undefined
getAttributeNS = undefined
getAttributeNames = undefined
getAttributeNode = undefined
getAttributeNodeNS = undefined
getBoundingClientRect = undefined
getClientRects = undefined
getElementsByClassName = undefined
getElementsByTagName = undefined
getElementsByTagNameNS = undefined
getHTML = undefined
hasAttribute = undefined
hasAttributeNS = undefined
hasAttributes = undefined
hasPointerCapture = undefined
insertAdjacentElement = undefined
insertAdjacentHTML = undefined
insertAdjacentText = undefined
matches = undefined
prepend = undefined
querySelector = undefined
querySelectorAll = undefined
releasePointerCapture = undefined
remove = undefined
removeAttribute = undefined
removeAttributeNS = undefined
removeAttributeNode = undefined
replaceChildren = undefined
replaceWith = undefined
requestFullscreen = undefined
requestPointerLock = undefined
scroll = undefined
scrollBy = undefined
scrollIntoView = undefined
scrollIntoViewIfNeeded = undefined
scrollTo = undefined
setAttribute = undefined
setAttributeNS = undefined
setAttributeNode = undefined
setAttributeNodeNS = undefined
setHTMLUnsafe = undefined
setPointerCapture = undefined
toggleAttribute = undefined
webkitMatchesSelector = undefined
webkitRequestFullScreen = undefined
webkitRequestFullscreen = undefined
currentCSSZoom = undefined
ariaColIndexText = undefined
ariaRowIndexText = undefined
getInnerHTML = undefined
nodeType = undefined
nodeName = undefined
baseURI = undefined
isConnected = undefined
ownerDocument = undefined
parentNode = undefined
parentElement = undefined
childNodes = undefined
firstChild = undefined
lastChild = undefined
previousSibling = undefined
nextSibling = undefined
nodeValue = undefined
textContent = undefined
ELEMENT_NODE = undefined
ATTRIBUTE_NODE = undefined
TEXT_NODE = undefined
CDATA_SECTION_NODE = undefined
ENTITY_REFERENCE_NODE = undefined
ENTITY_NODE = undefined
PROCESSING_INSTRUCTION_NODE = undefined
COMMENT_NODE = undefined
DOCUMENT_NODE = undefined
DOCUMENT_TYPE_NODE = undefined
DOCUMENT_FRAGMENT_NODE = undefined
NOTATION_NODE = undefined
DOCUMENT_POSITION_DISCONNECTED = undefined
DOCUMENT_POSITION_PRECEDING = undefined
DOCUMENT_POSITION_FOLLOWING = undefined
DOCUMENT_POSITION_CONTAINS = undefined
DOCUMENT_POSITION_CONTAINED_BY = undefined
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = undefined
appendChild = undefined
cloneNode = undefined
compareDocumentPosition = undefined
contains = undefined
getRootNode = undefined
hasChildNodes = undefined
insertBefore = undefined
isDefaultNamespace = undefined
isEqualNode = undefined
isSameNode = undefined
lookupNamespaceURI = undefined
lookupPrefix = undefined
normalize = undefined
removeChild = undefined
replaceChild = undefined
addEventListener = undefined
dispatchEvent = undefined
removeEventListener = undefined
Zawartość wygenerowana skryptem. Wystąpią różnice w zależności od wersji przeglądarki. script
- Element HTML, zawierający kod skryptu lub określenie pliku z kodem. Może być definiowany z atrybutami
src
itype
.
var
- Deklaracja ECMAScript, definiująca zmienną (lub zmienne oddzielone przecinkami).
=
- Operator ECMAScript, przypisuje argumentowi z lewej strony wartość z prawej strony.
Obiekt canvas
- Obiekt
- Typ danych.
- Metoda
- Funkcja obiektu.
- Własność
- Cecha obiektu.
getContext("2d")
- Metoda elementu
canvas
.Więcej
Metody i własności canvas 2d
canvas = [object HTMLCanvasElement]
globalAlpha = 1
globalCompositeOperation = source-over
filter = none
imageSmoothingEnabled = true
imageSmoothingQuality = low
strokeStyle = #000000
fillStyle = #000000
shadowOffsetX = 0
shadowOffsetY = 0
shadowBlur = 0
shadowColor = rgba(0, 0, 0, 0)
lineWidth = 1
lineCap = butt
lineJoin = miter
miterLimit = 10
lineDashOffset = 0
font = 10px sans-serif
textAlign = start
textBaseline = alphabetic
direction = ltr
fontKerning = auto
fontStretch = normal
fontVariantCaps = normal
letterSpacing = 0px
textRendering = auto
wordSpacing = 0px
clip = function clip() { [native code] }
createConicGradient = function createConicGradient() { [native code] }
createImageData = function createImageData() { [native code] }
createLinearGradient = function createLinearGradient() { [native code] }
createPattern = function createPattern() { [native code] }
createRadialGradient = function createRadialGradient() { [native code] }
drawFocusIfNeeded = function drawFocusIfNeeded() { [native code] }
drawImage = function drawImage() { [native code] }
fill = function fill() { [native code] }
fillText = function fillText() { [native code] }
getContextAttributes = function getContextAttributes() { [native code] }
getImageData = function getImageData() { [native code] }
getLineDash = function getLineDash() { [native code] }
getTransform = function getTransform() { [native code] }
isContextLost = function isContextLost() { [native code] }
isPointInPath = function isPointInPath() { [native code] }
isPointInStroke = function isPointInStroke() { [native code] }
measureText = function measureText() { [native code] }
putImageData = function putImageData() { [native code] }
reset = function reset() { [native code] }
roundRect = function roundRect() { [native code] }
save = function save() { [native code] }
scale = function scale() { [native code] }
setLineDash = function setLineDash() { [native code] }
setTransform = function setTransform() { [native code] }
stroke = function stroke() { [native code] }
strokeText = function strokeText() { [native code] }
transform = function transform() { [native code] }
translate = function translate() { [native code] }
arc = function arc() { [native code] }
arcTo = function arcTo() { [native code] }
beginPath = function beginPath() { [native code] }
bezierCurveTo = function bezierCurveTo() { [native code] }
clearRect = function clearRect() { [native code] }
closePath = function closePath() { [native code] }
ellipse = function ellipse() { [native code] }
fillRect = function fillRect() { [native code] }
lineTo = function lineTo() { [native code] }
moveTo = function moveTo() { [native code] }
quadraticCurveTo = function quadraticCurveTo() { [native code] }
rect = function rect() { [native code] }
resetTransform = function resetTransform() { [native code] }
restore = function restore() { [native code] }
rotate = function rotate() { [native code] }
strokeRect = function strokeRect() { [native code] }
Zawartość wygenerowana skryptem. Wystąpią różnice w zależności od wersji przeglądarki. zmienna
- Identyfikator ECMAScript.
<canvas width =
height =
id = >
<canvas>
.
(bez spacji).
Odczyt atrybutów szerokość i wysokość elementu
Zmień wielkość elementu
Domyślnym stylem wypełnienia jest kolor czarny. Możemy zdefiniować własny styl wypełnienia za pomocą własności canvas
.Zmień wielkość elementu
canvas
.
fillStyle
. Odpowiedni kod wpisujemy przed fragmentem określającym prostokąt.
Atrybuty szerokości i wysokości mogą być definiowane lub zmieniane w skrypcie.
Zmień wartości atrybutów.
Napisany kod możemy opublikować na stronie internetowej lub blogu. W pierwszym przypadku kod umieszczamy w elemencie Zmień wartości atrybutów.
body
, w drugim korzystamy z edytora i trybu HTML.Innym sposobem publikacji jest skopiowanie grafiki i stawienie pliku w formacie PNG. Niestety jesteśmy wtedy ograniczeni do grafiki statycznej.
W przykładzie dodano atrybuty
Pierwszy prostokąt, o wymiarach elementu
width
i height
definiujące odpowiednio szerokość i wysokość elementu canvas
.Pierwszy prostokąt, o wymiarach elementu
canvas
definiuje tło obrazu. Zmień wielkość elementu canvas
, dopasuj rozmiar tła.
Ćwiczenia
- Zapoznaj się z ćwiczeniami w aplikacji Kodujący Stwór.
Zadania
- W edytorze kodu utwórz stronę internetową zawierającą obraz canvas.