demo2s-6

Must Watch!



MustWatch



onwaiting Event

Example

Execute a JavaScript when the video stops because it needs to buffer the next frame: <video onwaiting="myFunction()">
Open in separate window
<html> <body> <p>This example demonstrates how to assign an "onwaiting" event to a video element.</p> <p>Play the video.</p> <video controls onwaiting="myFunction()"> <source src="radian.mp4" type="video/mp4"> <source src="radian.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video><!-- w w w . d e m o 2s . c o m--> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = "need to buffer the next frame"; } </script> </body> </html>

Description

The onwaiting event occurs when the video stops because it needs to buffer the next frame. This event can also be used on <audio> elements and <video> elements.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
onwaiting Yes Yes Yes Yes Yes Yes

Syntax

In HTML: <element onwaiting="myScript">
Open in separate window
<html> <body> <p>This example demonstrates how to assign an "onwaiting" event to a video element.</p> <p>Play the video.</p> <video controls onwaiting="myFunction()"> <source src="radian.mp4" type="video/mp4"> <source src="radian.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video><!-- w w w . de m o 2 s. c o m --> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = "need to buffer the next frame"; } </script> </body> </html> In JavaScript: object.onwaiting = function(){myScript};
Open in separate window
<html> <body> <p>This example uses the HTML DOM to assign an "onwaiting" event to a video element.</p> <p>Play the video.</p> <video controls id="myVideo"> <source src="radian.mp4" type="video/mp4"> <source src="radian.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video><!-- w w w. d e m o 2s . c o m --> <p id='demo'></p> <script> document.getElementById("myVideo").onwaiting = function() {myFunction()}; function myFunction() { document.getElementById('demo').innerHTML = "need to buffer the next frame"; } </script> </body> </html> In JavaScript, using the addEventListener() method: object.addEventListener("waiting",myScript);
Open in separate window
<html> <body> <p>This example uses the addEventListener() method to attach a "waiting" event to a video element.</p> <p>Play the video.</p> <video controls id="myVideo"> <source src="radian.mp4" type="video/mp4"> <source src="radian.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video><!-- w w w . de m o 2 s . co m--> <p id='demo'></p> <script> document.getElementById("myVideo").addEventListener("waiting", myFunction); function myFunction() { document.getElementById('demo').innerHTML = "need to buffer the next frame"; } </script> </body> </html>

Technical Details

Item Value
Bubbles: No
Cancelable: No
Event type: Event
Supported HTML tags: <audio>, <video>
DOM Version: Level 3 Events

onwheel Event

Example

When the user rolls the mouse wheel over a <div> element, change its font-size: document.getElementById("myDIV").addEventListener("wheel", myFunction); function myFunction() { this.style.fontSize = "35px"; }
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w .d e m o 2 s . c o m --> border: 1px solid black; } </style> </head> <body> <div id="myDIV">This example uses the addEventListener() method to attach a "wheel" event to a DIV element. Roll the mouse wheel over me - either up or down!</div> <script> document.getElementById("myDIV").addEventListener("wheel", myFunction); function myFunction() { this.style.fontSize = "35px"; } </script> </body> </html>

Description

The onwheel event occurs when the mouse wheel is rolled up or down over an element. The onwheel event also occurs when the user scrolls or zooms in or out of an element by using a touch pad.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
onwheel Yes Yes Yes Yes Yes Yes

Syntax

In HTML: <element onwheel="myScript">
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2 s. c om --> border: 1px solid black; } </style> </head> <body> <div id="myDIV" onwheel="myFunction()">This example demonstrates how to assign an "onwheel" event event to a DIV element. Roll the mouse wheel over me - either up or down!</div> <script> function myFunction() { document.getElementById("myDIV").style.fontSize = "35px"; } </script> </body> </html> In JavaScript: object.onwheel = function(){ myScript};
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o2 s . c om --> border: 1px solid black; } </style> </head> <body> <div id="myDIV">This example uses the HTML DOM to assign an "onwheel" event to a DIV element. Roll the mouse wheel over me - either up or down!</div> <script> document.getElementById("myDIV").onwheel = function() {myFunction()}; function myFunction() { document.getElementById("myDIV").style.fontSize = "35px"; } </script> </body> </html> In JavaScript, using the addEventListener() method: object.addEventListener("wheel", myScript);
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2 s. c o m --> border: 1px solid black; } </style> </head> <body> <div id="myDIV">This example uses the addEventListener() method to attach a "wheel" event to a DIV element. Roll the mouse wheel over me - either up or down!</div> <script> document.getElementById("myDIV").addEventListener("wheel", myFunction); function myFunction() { this.style.fontSize = "35px"; } </script> </body> </html>

Technical Details

Item Value
Bubbles: Yes
Cancelable: Yes
Event type: WheelEvent
Supported HTML tags: All HTML elements
DOM Version: Level 3 Events

DOM Element Element Objects

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.

Property List

Property Description
accessKeygets and sets the accesskey attribute of an element
attributesGet all attributes
childElementCountcount child Element
childNodes Get all child Nodes
children get children elements
classList get style class List
className gets and sets the class name
clientHeight get viewable Height
clientLeftget viewable Left position
clientTop get viewable Top position
clientWidth get viewable Width
contentEditable gets and sets whether an element is editable or not
dirgets and sets the dir attribute of an element
firstChild Get first Child Node
firstElementChildget first Element Child
id Get and Set id Property
innerHTML Get and Set HTML content
innerTextGet element content as Text
isContentEditable Check if an element is editable or not
lang Get and Set element language Property
lastChildGet last Child
lastElementChild get last Element Child
length Get Element child element count/length Property
namespaceURI Get and Set namespace URI
nextElementSibling get next Element Sibling
nextSibling Get next Sibling element
nodeName Get node Name
nodeType Get node Type
nodeValue Get and Set node Value
offsetHeight get offset Height
offsetLeft get offset Left on screen
offsetParentget offset Parent position on screen
offsetTopget offset top position
offsetWidth get offset Width on screen
outerHTML Get and Set Element HTML and its children
outerText Get and Set text value via outer txt
ownerDocumentGet parent Document
parentElement Get parent Element
parentNode Get parent Node
previousElementSibling get previous Element Sibling element
previousSiblingGet previous Sibling node
scrollHeight get Height in scrolling
scrollLeftget scrolled Left position
scrollTop get scrolled Top position
scrollWidth get scrolled Width
style Get and Set style Property
tabIndex Get and Set tab Index Property
tagName get tag Name
textContent Get and Set text Content
title Get and Set title Property

Method List

Method Description
addEventListener() add Event Listener
appendChild() append Child element
blur()remove focus from an element
click() simulates a mouse-click on an element
cloneNode clone Node
closest() Get closest element by CSS selector
compareDocumentPosition compare Document Position
contains() Check if element contains another element
exitFullscreen() exit Full screen mode
focus() grab focus
getAttribute() get Attribute by name
getAttributeNode() get Attribute Node by name
getBoundingClientRect() get Bounding Client Rectangle
getElementsByClassName() get children Elements By Class Name
getElementsByTagName() get children Elements By Tag Name
hasAttribute() check Attribute existence by name
hasAttributes Check if element has a certain Attribute
hasChildNodes Check if element has Child Nodes
insertAdjacentElement()insert Adjacent Element
insertAdjacentHTML() insert HTML
insertAdjacentText() insert text node
insertBeforeinsert node Before
isDefaultNamespace Check if element has Default Namespace
isEqualNode is Equal to another Node
isSameNode is Same Node with another element
isSupportedCheck if element is Supported a feature
matches()matches children elements by CSS selector
normalizenormalize element content
querySelector() get children elements via CSS Selector
querySelectorAll() Get all children elements by CSS Selector
removeremove element from DOM tree
removeAttribute() remove Attribute by name
removeAttributeNode()remove Attribute Node by name
removeChild remove Child element node
removeEventListener()remove Event Listener
replaceChild replace Child element
requestFullscreen() request Full screen mode
scrollIntoView() scroll Into visible
setAttribute() set Attribute
setAttributeNode() set Attribute Node

DOM Document Objects

The Document Object

When an HTML document is loaded into a web browser, it becomes a document object. The document object is the root node of the HTML document.

Property List

Property Description
activeElement Get currently focused element in the document
addEventListener()attaches an event handler to the document
baseURIreturns the base URI of the HTML document
body gets and sets the document's body
cookiegets and sets cookies in the current document
characterSetGet the character encoding for the document
createAttribute() creates an attribute
createDocumentFragment() creates an imaginary Node object
defaultViewGet the document's Window Object
designMode gets and sets whether the document is editable or not
doctypeGet doctype of HTML document as a DocumentType object
documentElementGet documentElement of the document as Element object
documentURIgets and sets the location of a document
domain Get the domain name that loaded the current document
fullscreenElementGet the current element displayed in full screen mode
headGet <head> element of the current document.
lastModified Get last Modified time
readyState Check if document is loaded
referrerGet URL of the document that loaded the current document
title Get document title Property
URL Get full URL of the current HTML document
implementation Get implementation information
inputEncoding Get character encoding for the document
strictErrorChecking Get strict Error Checking Property

Method List

Method Description
adoptNode() adopts a node from another document
close()closes the output stream
createComment() create Comment node
createElement() create Element Node
createEvent() Event create Event Object
createTextNode() create Text Node
execCommand() executes command for an editable section
fullscreenEnabled() Check if fullscreen mode is Enabled
getElementById()finds the element by its ID attribute value
getElementsByClassName() Get a collection of all elements
getElementsByTagName() Get all elements from document with the specified tag name
getElementsByName() Get all elements with the specified name
hasFocus() Check whether the document or any children element has focus
importNode() imports a node from another document
normalize normalize element and text node
normalizeDocument() normalize Document
querySelector() Get elements by CSS selector(s)
querySelectorAll()Get all elements from CSS selector(s)
removeEventListener() remove Event Listener
renameNode()rename Node
open() opens an output stream
write() writes HTML expressions
writeln() writes HTML expressions with new line character

Collection List

Collection Description
anchors CollectionDocument Get anchors Collection
applets Collection Document Get applets Collection
embeds Collection Document Get embeds Collection
forms Collection Document Get forms Collection
images Collection Document Get images Collection
links Collection Document Get links Collection
scripts Collection Document Get scripts Collection

DOM Attribute Objects

In the HTML DOM, the Attr object represents an HTML attribute. An HTML attribute always belongs to an HTML element.

The NamedNodeMap Object

In the HTML DOM, the NamedNodeMap object represents an unordered collection of an elements attribute nodes. Nodes in a NamedNodeMap can be accessed by name or by index (number).

Properties and Methods

Property / Method Description
isId Returns true if the attribute is of type Id,
otherwise it returns false
name Returns the name of an attribute
value gets or sets the value of the attribute
specified Returns true if the attribute has been specified,
otherwise it returns false
getNamedItem() Returns a specified attribute node from a NamedNodeMap
item() Returns the attribute node at a specified index in a NamedNodeMap
length Returns the number of attribute nodes in a NamedNodeMap
removeNamedItem() Removes a specified attribute node
setNamedItem() Sets the specified attribute node (by name)

DOM HTMLCollection

An HTMLCollection object is an array-like list of HTML elements. Methods like the getElementsByTagName() returns an HTMLCollection.

Properties and Methods

The following properties and methods can be used on a HTMLCollection object:
Property / Method Description
item()Returns the element at the specified index in an HTMLCollection
length Returns the number of elements in an HTMLCollection
namedItem() Returns the element with the specified ID, or name, in an HTMLCollection

Example

Get an HTMLCollection: // Returns a collection of all the P elements in the document let x = document.getElementsByTagName("P");
Open in separate window
<html> <body> <h1>The HTMLCollection Object</h1> <p>Use the getElementsByTagName() method to return an HTMLCollection:</p> <script> let x = document.getElementsByTagName("P"); document.write(x); </script> </body> </html>

Example

Write the number of <p> elements in the document: let x = document.getElementsByTagName("P"); document.write(x.length);
Open in separate window
<html> <body> <h1>The HTMLCollection Object</h1> <p>Use the getElementsByTagName() method to return an HTMLCollection.</p> <p>The number of P elements on this page:</p> <script> let x = document.getElementsByTagName("P"); document.write(x.length); </script> </body> </html>

Example

Loop through every element in an HTMLCollection: let x, i, l; x = document.getElementsByTagName("*"); l = x.length; for (i = 0; i < l; i++) { document.write(x[i].tagName + "<br>"); }
Open in separate window
<html> <body> <h1>The HTMLCollection Object</h1> <p>Loop through each HTML element on this page, and write its tag name:</p> <script> let x, i, l; x = document.getElementsByTagName("*"); l = x.length; for (i = 0; i < l; i++) { document.write(x[i].tagName + "<br>"); } </script> </body> </html>

DOM Span Object

The Span object represents an HTML <span> element.

Access a Span Object

let x = document.getElementById("mySpan");
Open in separate window
<html> <body> <h3>A demonstration of how to access a SPAN element</h3> <p>this is a <span id="mySpan" style="color:blue;">test</span>....</p> <p>Click the button to get the color of the span element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {<!-- w w w .d e m o 2 s . c om --> let x = document.getElementById("mySpan").style.color; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Span Object

You can create a <span> element by using the document.createElement() method: let x = document.createElement("SPAN");
Open in separate window
<html> <body> <p>Click the button to create a SPAN element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("SPAN"); let t = document.createTextNode("This is a span element."); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Strong Object

The Strong object represents an HTML <strong> element.

Access a Strong Object

let x = document.getElementById("myStrong");
Open in separate window
<html> <body> <h3>A demonstration of how to access a STRONG element</h3> <p>Click the button to set the color of <strong id="myStrong">this strong text</strong> to red.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("myStrong"); x.style.color = "red"; } </script> </body> </html>

Create a Strong Object

You can create a <strong> element by using the document.createElement() method: let x = document.createElement("STRONG");
Open in separate window
<html> <body> <p>Click the button to create a STRONG element with some text.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("STRONG"); let t = document.createTextNode("Some strong text"); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Subscript Object

The Subscript object represents an HTML <sub> element.

Access a Subscript Object

let x = document.getElementById("mySub");
Open in separate window
<html> <body> <h3>A demonstration of how to access a SUB element</h3> <p>Click the button to set the color of <sub id="mySub">this subscript text</sub> to red.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("mySub"); x.style.color = "red"; } </script> </body> </html>

Create a Subscript Object

You can create a <sub> element by using the document.createElement() method: let x = document.createElement("SUB");
Open in separate window
<html> <body> <p>Click the button to create a SUB element with some text.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("SUB"); let t = document.createTextNode("This text contains subscript text"); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Summary Object

The Summary object represents an HTML <summary> element.

Access a Summary Object

let x = document.getElementById("mySummary");
Open in separate window
<html> <body> <h3>A demonstration of how to access a SUMMARY element</h3> <details> <summary id="mySummary">CSS.</summary> <p> - This is a test.</p> </details><!-- w ww . d e m o 2 s . c o m --> <p>Click the "Test" button to get the HTML content of the summary element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("mySummary").innerHTML; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Summary Object

You can create a <summary> element by using the document.createElement() method: let x = document.createElement("SUMMARY");
Open in separate window
<html> <body> <p>Click the button to create a DETAILS, a SUMMARY and a P element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() {<!-- ww w. d e m o 2 s .c o m --> let x = document.createElement("DETAILS"); document.body.appendChild(x); let summaryElmnt = document.createElement("SUMMARY"); let txt1 = document.createTextNode("CSS."); summaryElmnt.appendChild(txt1); let pElmnt = document.createElement("P"); let txt2 = document.createTextNode(" - This is a test."); pElmnt.appendChild(txt2); x.appendChild(summaryElmnt); x.appendChild(pElmnt); } </script> </body> </html>

DOM Superscript Object

The Superscript object represents an HTML <sup> element.

Access a Superscript Object

let x = document.getElementById("mySup");
Open in separate window
<html> <body> <h3>A demonstration of how to access a SUP element</h3> <p>Click the button to set the color of <sup id="mySup">this superscript text</sup> to red.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("mySup"); x.style.color = "red"; } </script> </body> </html>

Create a Superscript Object

You can create a <sup> element by using the document.createElement() method: let x = document.createElement("SUP");
Open in separate window
<html> <body> <p>Click the button to create a SUP element with some text.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("SUP"); let t = document.createTextNode("This text contains superscript text"); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Table Object

The Table object represents an HTML <table> element.

Access a Table Object

let x = document.getElementById("myTable");
Open in separate window
<html> <head> <style> table, td { border: 1px solid black; } </style><!-- w w w . de m o 2 s . c o m--> </head> <body> <h3>A demonstration of how to access a TABLE element</h3> <table id="myTable"> <tr> <td>cell 1</td> <td>cell 2</td> </tr> <tr> <td>cell 3</td> <td>cell 4</td> </tr> </table> <p>Click the button to remove the first row in the table.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("myTable"); x.deleteRow(0); } </script> </body> </html>

Create a Table Object

You can create a <table> element by using the document.createElement() method: let x = document.createElement("TABLE");
Open in separate window
<html> <head> <style> table, td { border: 1px solid black; } </style><!-- w w w . d em o 2 s . c o m--> </head> <body> <p>Click the button to create a TABLE, a TR and a TD element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TABLE"); x.setAttribute("id", "myTable"); document.body.appendChild(x); let y = document.createElement("TR"); y.setAttribute("id", "myTr"); document.getElementById("myTable").appendChild(y); let z = document.createElement("TD"); let t = document.createTextNode("cell"); z.appendChild(t); document.getElementById("myTr").appendChild(z); } </script> </body> </html>

Collection List

Collections Description
cells Table Get cells Collection
rows Table Get rows Collection
tBodies Table Get tBodies Collection
cells Table Get cells Collection

Property List

Property Description
caption DOM Table Get and Set caption table title Property
tFoot DOM Table Get and Set table Foot Property
tHead DOM Table Get and Set table Head Property

Method List

Method Description
createCaption() Table create Caption Method
createFoot() Table create table Foot Method
createHead() Table create Table Head Method
deleteCaption() Table delete table title Caption Method
deleteRow() Table delete Row Method
deleteFoot() Table delete Table Foot Method
deleteHead() Table delete Table Head Method
insertRow() Table insert Row Method

DOM TBody Object

The TBody object represents an HTML <tbody> element.

Access a TBody Object

let x = document.getElementById("myTBody");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w .d e m o 2 s . c o m --> </head> <body> <h3>A demonstration of how to access a TBODY element</h3> <table> <tbody id="myTBody"> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </tbody> </table> <p>Click the button to change the style of the TBODY element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myTBody"); x.style.color = "red"; } </script> </body> </html>

Create a TBody Object

You can create a <tbody> element by using the document.createElement() method: let x = document.createElement("TBODY");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w .d e m o 2 s . c o m--> </head> <body> <table id="myTable"> </table> <p>Click the button to create a TBODY element and a TR and a TD.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TBODY"); let y = document.createElement("TR"); let z = document.createElement("TD"); z.innerHTML = "A table cell inside a tr inside a tbody inside a table!" y.appendChild(z); x.appendChild(y); document.getElementById("myTable").appendChild(x); } </script> </body> </html>

DOM TableData Object

The TableData object represents an HTML <td> element.

Access a TableData Object

let x = document.getElementById("myTd");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- ww w .d e m o 2 s . c o m--> </head> <body> <h3>A demonstration of how to access a TD element</h3> <table> <tr> <td id="myTd">Cell 1</td> <td>Cell 2</td> </tr> </table> <p>Click the button to change the text of the first TD element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myTd"); x.innerHTML = "NEW CELL CONTENT"; } </script> </body> </html> You can also access a <td> element by searching through the cells collection of a table row.

Create a TableData Object

You can create a <td> element by using the document.createElement() method: let x = document.createElement("TD");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d em o 2 s . c o m --> </head> <body> <table id="myTable"> <tr id="myTr"> </tr> </table> <p>Click the button to create a TD element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TD"); let t = document.createTextNode("new cell"); x.appendChild(t); document.getElementById("myTr").appendChild(x); } </script> </body> </html>

Property List

Property Description
cellIndexTableData Get and Set cell Index Property
colSpan TableData Get and Set column Span Property
headers TableData Get and Set headers collection Property
rowSpanTableData Get and Set row Span Property

DOM Textarea Object

The Textarea object represents an HTML <textarea> element.

Access a Textarea Object

let x = document.getElementById("myTextarea");
Open in separate window
<html> <body> <h3>A demonstration of how to access a TEXTAREA element</h3> Address:<br> <textarea id="myTextarea"> this is a test from demo2s.com </textarea> <p>Click the button to get the content of the text area.</p> <button type="button" onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {<!-- w w w . d e m o 2 s . c o m--> let x = document.getElementById("myTextarea").value; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Textarea Object

You can create a <textarea> element by using the document.createElement() method: let x = document.createElement("TEXTAREA");
Open in separate window
<html> <body> <p>Click the button to create a TEXTAREA element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TEXTAREA"); let t = document.createTextNode("this is a test."); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

Property List

Property Description
autofocus Textarea Get and Set auto focus Property
cols Textarea Get and Set column size Property
defaultValue Textarea Get and Set default Value Property
disabled Textarea enable and disable text area box
form Textarea Get form Property
maxlength Textarea Get and Set max Length Property
name Textarea Get and Set name Property
placeholderTextarea Get and Set placeholder Property
readonly Textarea Get and Set readOnly Property
required Textarea Get and Set required Property
rows Textarea Get and Set row size Property
type Textarea Get and Set type Property
valueTextarea Get and Set value Property
wrap Textarea Get and Set wrap Property

Method List

Method Description
select() select all text

DOM TFoot Object

The TFoot object represents an HTML <tfoot> element.

Access a TFoot Object

let x = document.getElementById("myTFoot");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e m o 2 s . c o m --> </head> <body> <h3>A demonstration of how to access a TFOOT element</h3> <table> <thead> <tr> <th>Header 1</th> <th>Header 2</th> </tr> </thead> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </tbody> <tbody id="myTFoot"> <tr> <td>Footer 1</td> <td>Footer 2</td> </tr> </tbody> </table> <p>Click the button to change the style of the TFOOT element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myTFoot"); x.style.color = "red"; } </script> </body> </html>

Create a TFoot Object

You can create a <tfoot> element by using the document.createElement() method: let x = document.createElement("TFOOT");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e mo 2s . c o m --> </head> <body> <table id="myTable"> <thead> <tr> <th>Header</th> </tr> </thead> <tbody> <tr> <td>Cell 1</td> </tr> <tr> <td>Cell 2</td> </tr> </tbody> </table> <p>Click the button to create a TFOOT element and a TR and a TD.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TFOOT"); let y = document.createElement("TR"); let z = document.createElement("TD"); z.innerHTML = "A Footer!" y.appendChild(z); x.appendChild(y); document.getElementById("myTable").appendChild(x); } </script> </body> </html>

DOM TableHeader Object

The TableHeader object represents an HTML <th> element.

Access a TableHeader Object

let x = document.getElementById("myTh");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e m o 2 s . c om --> </head> <body> <h3>A demonstration of how to access a TH element</h3> <table> <tr> <th id="myTh">Name</th> </tr> <tr> <td>CSS</td> </tr> </table> <p>Click the button to change the text of the TH element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myTh"); x.innerHTML = "New Table Header"; } </script> </body> </html> You can also access a <th> element by searching through the cells collection of a table row.

Create a TableHeader Object

You can create a <th> element by using the document.createElement() method: let x = document.createElement("TH");
Open in separate window
<html> <head> <style> table, th { border: 1px solid black; } </style><!-- w w w . d e m o 2 s . c o m--> </head> <body> <table id="myTable"> <tr id="myTr"> </tr> </table> <p>Click the button to create a TH element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TH"); let t = document.createTextNode("table header cell"); x.appendChild(t); document.getElementById("myTr").appendChild(x); } </script> </body> </html>

Property List

Property Description
abbr Javascript DOM TableHeader Get and Set abbreviation Property
cellIndex Javascript DOM TableHeader Get and Set cell Index Property
colSpanJavascript DOM TableHeader Get and Set column Span Property
headers Javascript DOM TableHeader Get and Set headers collection Property
rowSpan Javascript DOM TableHeader Get and Set row Span Property

DOM THead Object

The THead object represents an HTML <thead> element.

Access a THead Object

let x = document.getElementById("myTHead");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e m o 2 s .c o m --> </head> <body> <h3>A demonstration of how to access a THEAD element</h3> <table> <thead id="myTHead"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> </thead> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </tbody> </table> <p>Click the button to change the style of the THEAD element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myTHead"); x.style.color = "red"; } </script> </body> </html>

Create a THead Object

You can create a <thead> element by using the document.createElement() method: let x = document.createElement("THEAD");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e mo 2 s . co m --> </head> <body> <table id="myTable"> <tbody> <tr> <td>Cell 1</td> </tr> <tr> <td>Cell 2</td> </tr> </tbody> </table> <p>Click the button to create a THEAD element and a TR and a TD.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("THEAD"); let y = document.createElement("TR"); let z = document.createElement("TD"); z.innerHTML = "Header" y.appendChild(z); x.appendChild(y); document.getElementById("myTable").appendChild(x); } </script> </body> </html>

DOM Time Object

The Time object represents an HTML <time> element.

Access a Time Object

let x = document.getElementById("myTime");
Open in separate window
<html> <body> <h3>A demonstration of how to access a TIME element</h3> <p>Test is on <time id="myTime" datetime="2020-03-01"> March 1st</time>.</p> <p>Click the button to get the HTML content of the time element above.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {<!-- w w w . d e m o 2 s . c o m--> let x = document.getElementById("myTime").innerHTML; document.getElementById("demo").innerHTML = x; } </script> </body> </html> The time element does not render as anything special in any of the major browsers. The dateTime property is only supported in Firefox.

Create a Time Object

You can create a <time> element by using the document.createElement() method: let x = document.createElement("TIME");
Open in separate window
<html> <head> </head><!-- w w w . d e m o 2 s . c o m --> <body> <p>Click the button to create a TIME element that specifies the date of "Christmas day (2020-12-25)".</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TIME"); x.setAttribute("datetime", "2020-12-25"); let t = document.createTextNode("Christmas day"); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

Property List

PropertyDescription
dateTime Time Get and Set date Time Property

DOM Title Object

The Title object represents an HTML <title> element.

Access a Title Object

let x = document.getElementsByTagName("TITLE")[0];
Open in separate window
<html> <head> <title>HTML DOM Objects</title> </head><!-- w w w . d e m o 2 s . c o m --> <body> <h3>A demonstration of how to access a TITLE element</h3> <p>Click the button to get the text of the document's title.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementsByTagName("TITLE")[0].text; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Title Object

You can create a <title> element by using the document.createElement() method: let x = document.createElement("TITLE");
Open in separate window
<html> <head> </head><!-- w ww . d e m o 2s . c o m --> <body> <p>Click the button to create a TITLE element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.createElement("TITLE"); let t = document.createTextNode("HTML DOM Objects"); x.appendChild(t); document.head.appendChild(x); document.getElementById("demo").innerHTML = "created a TITLE element in the HEAD section of your document."; } </script> </body> </html>

Property List

Property Description
text Title Get and Set text Property

DOM TableRow Object

The TableRow object represents an HTML <tr> element.

Access a TableRow Object

let x = document.getElementById("myTr");
Open in separate window
<html> <head> <style> table, th, td { border: 1px solid black; } </style><!-- w w w . d e m o 2 s. c o m--> </head> <body> <h3>A demonstration of how to access a TR element</h3> <table> <tr id="myRow"> <td>First cell</td> <td>Second cell</td> <td>Third cell</td> </tr> </table> <p>Click the button to delete the first cell from the table row.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let row = document.getElementById("myRow"); row.deleteCell(0); } </script> </body> </html> You can also access a <tr> element by searching through the rows collection of a table.

Create a TableRow Object

You can create a <tr> element by using the document.createElement() method: let x = document.createElement("TR");
Open in separate window
<html> <head> <style> table, td { border: 1px solid black; } </style><!-- w w w. d e m o 2 s . c o m--> </head> <body> <table id="myTable"> </table> <p>Click the button to create a TR and a TD element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("TR"); x.setAttribute("id", "myTr"); document.getElementById("myTable").appendChild(x); let y = document.createElement("TD"); let t = document.createTextNode("new cell"); y.appendChild(t); document.getElementById("myTr").appendChild(y); } </script> </body> </html>

Property List

Property Description
rowIndexDOM TableRow Get and Set row Index Property
sectionRowIndex DOM TableRow Get and Set row section Index Property

Method List

Method Description
deleteCell()DOM TableRow delete Cell Method
insertCell()DOM TableRow insert Cell Method

DOM Track Object

The Track object represents an HTML <track> element. let x = document.getElementById("myTrack");

Create a Track Object

You can create a <track> element by using the document.createElement() method: let x = document.createElement("TRACK");

Property List

Property Description
default Track Get and Set default value Property
kind Track Get and Set kind Property
label Track Get and Set label Property
readyState Track Get and Set ready State Property
src Track Get and Set source url Property
srclang Track Get and set source lang Property

DOM Underline Object

The Underline object represents an HTML <u> element.

Access an Underline Object

let x = document.getElementById("myU");
Open in separate window
<html> <body> <h3>A demonstration of how to access a U element</h3> <p>Click the button to set the color of <u id="myU">this underlined text</u> to red.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("myU"); x.style.color = "red"; } </script> </body> </html>

Create an Underline Object

You can create a <u> element by using the document.createElement() method: let x = document.createElement("U");
Open in separate window
<html> <body> <p>Click the button to create a U element with some text.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("U"); let t = document.createTextNode("This text is underlined"); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Ul Object

The Ul object represents an HTML <ul> element. let x = document.getElementById("myUL");
Open in separate window
<html> <body> <h3>A demonstration of how to access a UL element</h3> <ul id="myUL"> <li>A</li> <li>B</li> <li>C</li> </ul><!-- w w w . d e m o 2 s . c o m --> <p>Click the button to get the id of the unordered list.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myUL").id; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Ul Object

You can create a <ul> element by using the document.createElement() method: let x = document.createElement("UL");
Open in separate window
<html> <body> <p>Click the button to create a UL and LI element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() {<!-- w w w .d e mo 2 s . c o m --> let x = document.createElement("UL"); x.setAttribute("id", "myUL"); document.body.appendChild(x); let y = document.createElement("LI"); let t = document.createTextNode("A"); y.appendChild(t); document.getElementById("myUL").appendChild(y); } </script> </body> </html>

DOM Variable Object

The Variable object represents an HTML <var> element.

Access a Variable Object

let x = document.getElementById("myVar");
Open in separate window
<html> <body> <h3>A demonstration of how to access a let element</h3> <p>Click the button to set the color of <var id="myVar">this text</var> to red.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.getElementById("myVar"); x.style.color = "red"; } </script> </body> </html>

Create a Variable Object

You can create a <var> element by using the document.createElement() method: let x = document.createElement("VAR");
Open in separate window
<html> <body> <p>Click the button to create a let element with some text.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { let x = document.createElement("VAR"); let t = document.createTextNode("Some text.."); x.appendChild(t); document.body.appendChild(x); } </script> </body> </html>

DOM Video Object

The Video object represents an HTML <video> element.

Access a Video Object

let x = document.getElementById("myVideo");
Open in separate window
<html> <body> <h3>A demonstration of how to access a VIDEO element</h3> <video id="myVideo" width="320" height="240" controls> <source src="radian.mp4" type="video/mp4"> <source src="radian.ogg" type="video/ogg"> Your browser does not support the video tag. </video><!-- w w w . d e m o 2 s . c o m --> <p>Click the button to get the duration of the video, in seconds.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementById("myVideo").duration; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Video Object

You can create a <video> element by using the document.createElement() method: let x = document.createElement("VIDEO");
Open in separate window
<html> <body> <p>Click the button to create a VIDEO element with controls that will play a movie in a .mp3 or .ogg file format depending on browser support.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() {<!-- w w w . d e m o 2 s . c o m --> let x = document.createElement("VIDEO"); if (x.canPlayType("video/mp4")) { x.setAttribute("src","radian.mp4"); } else { x.setAttribute("src","radian.ogg"); } x.setAttribute("width", "320"); x.setAttribute("height", "240"); x.setAttribute("controls", "controls"); document.body.appendChild(x); } </script> </body> </html>

Video Property List

PropertyDescription
audioTracks Video Get and Set audio Tracks Property
autoPlay Video Get and Set auto play Property
buffered Video Get and Set if to buffer video
controller Video Get and Set controller object
controls Video Show and hide controls panel
currentSrc Video Get and Set current source url Property
currentTime Video Get and Set current played Time Property
muted Video Get and Set default Muted state
defaultPlaybackRate Video Get and Set default Playback Rate Property
duration Video Get and Set duration Property
ended Video Get and Set ended state
error Video Get error Property
height Video Get and Set height Property
loop Video Get and Set loop Property
mediaGroup Video Get and Set media Group Property
muted Video Get and Set muted state
networkState Video Get network State Property
paused Video Get and Set paused state
playbackRate Video Get and Set playback Rate Property
played Video Check if played Property
poster Video Get and Set poster image Property
preload Video Get and Set preload flag
readyState Video Get ready State Property
seekable Video Get seekable Property
seeking Video Get seeking state Property
src Video Get and Set source url
startDate Video Get and Set start Date Property
textTracks Video Get and Set text Tracks Property
videoTracks Video Get and Set video Tracks Property
volume Video Get and Set volume Property
width Video Get and Set width Property

Video Method List

PropertyDescription
addTextTrack() Video add Text Track Method
checkPlayableType() Video check Playable Type Method
load() Video load video Method
pause() Video pause video Method
play() Video play video Method

DOM Style object

The Style object represents an individual style statement.

Access a Style Object

The Style object can be accessed from the head section of the document, or from specific HTML element(s). Accessing style object(s) from the head section of the document:

Example

let x = document.getElementsByTagName("STYLE");
Open in separate window
<html> <head> <style> body {<!-- w w w . d e m o 2 s . c om --> background-color: yellow; color: red; } </style> </head> <body> <p>Click the button to display the style properties of this document.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { let x = document.getElementsByTagName("STYLE")[0]; document.getElementById("demo").innerHTML = x.innerHTML; } </script> </body> </html> Accessing a specified element's style object: let x = document.getElementById("myH1").style;
Open in separate window
<html> <body> <h1 id="myH1" style="color:red">My Header</h1> <p>Click the button to get the style property of the H1 element.</p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {<!-- w w w . d e mo 2 s . c o m --> let x = document.getElementById("myH1").style.color; document.getElementById("demo").innerHTML = x; } </script> </body> </html>

Create a Style Object

You can create a <style> element by using the document.createElement() method:

Example

let x = document.createElement("STYLE");
Open in separate window
<html> <head> </head><!-- w w w . d e m o2 s . c o m --> <body> <p>Click the button to create a STYLE element, and place it in the head section.</p> <button onclick="myFunction()">Test</button> <p>The created style element contains css declarations that will change the font properties of this document.</p> <script> function myFunction() { let x = document.createElement("STYLE"); let t = document.createTextNode("body {font: 20px yellow;}"); x.appendChild(t); document.head.appendChild(x); } </script> </body> </html> You can also set the style properties of an existing element: document.getElementById("myH1").style.color = "red";
Open in separate window
<html> <body> <h1 id="myH1">How to change the style of a header</h1> <p>Click the button to change the style of the H1 element.</p> <button onclick="myFunction()">Test</button> <script> function myFunction() { document.getElementById("myH1").style.color = "red"; } </script> </body> </html>

CSSStyleDeclaration Object

The CSSStyleDeclaration object represents a collection of CSS property-value pairs.

Property List

Property Description
cssTextGet and Set css Text Property
length Get and Set number of style
parentRule Get and Set parent Rule Property
item Method Get style rule by index

Method List

Method Description
getPropertyPriority get CSS Rule Priority
getPropertyValue get Style rule Property
removeProperty remove style rule Property
setProperty set rule Property

DOM Style top Property

Example

Set the top position of a <button> element: document.getElementById("myBtn").style.top = "100px";
Open in separate window
<html> <head> <style> #myBtn {<!-- w ww . de m o 2 s . c o m--> position: absolute; } </style> </head> <body> <button type="button" id="myBtn" onclick="myFunction()"> Set top position to 100 px</button> <script> function myFunction() { document.getElementById("myBtn").style.top = "100px"; } </script> </body> </html>

Description

The top property gets and sets the top position of a positioned element. This property sets the top position of the element including padding, scrollbar, border and margin. A positioned element is an element with the position property set to: relative, absolute, or fixed. To set or get the bottom position of a positioned element, use the bottom property.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
top Yes Yes Yes Yes Yes Yes

Syntax

Return the top property: object.style.top Set the top property: object.style.top = "auto|length|%|initial|inherit"

Property Values

Value Description
auto Lets the browser set the top position.
This is default
length Defines the top position in length units.
Negative values are allowed
% Sets the top position in % of the height of the parent element
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the top position of a positioned element.

More Examples

Using negative values - Set the top position of a <div> element: document.getElementById("myDiv").style.top = "-100px";
Open in separate window
<html> <head> <style> #myDiv {<!-- w w w . d e mo 2 s . c o m --> border: 1px solid #FF0000; position: relative; } </style> </head> <body> <div id="myDiv">This is a div.</div> <br> <button type="button" onclick="myFunction()"> Set top position of div to -10 px</button> <script> function myFunction() { document.getElementById("myDiv").style.top = "-10px"; } </script> </body> </html>

Example

Return the top position of a <div> element: console.log(document.getElementById("myDiv").style.top);
Open in separate window
<html> <body> <div id="myDiv" style="position:absolute;top:75px;">This is a div.</div> <button type="button" onclick="myFunction()"> Return top position of div</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myDiv").style.top; } </script> </body> </html>

DOM Style transform Property

Example

Rotate a div element: document.getElementById("myDIV").style.transform = "rotate(7deg)";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o2 s .c o m--> margin: auto; border: 1px solid black; width: 200px; height: 100px; background-color: coral; color: white; } </style> </head> <body> <p>Click the "Test" button to rotate the DIV element:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { // Code for IE9 document.getElementById("myDIV").style.msTransform = "rotate(20deg)"; // Standard syntax document.getElementById("myDIV").style.transform = "rotate(20deg)"; } </script> </body> </html>

Description

The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transform Yes Yes Yes Yes Yes Yes

Syntax

Return the transform property: let a = object.style.transform; Set the transform property: object.style.transform = "none|transform-functions|initial|inherit"

Property Values

Value Description
none there should be no transformation
matrix(n, n, n, n, n, n) a 2D transformation, using a matrix of six values
matrix3d(n, n, n, n, etc....) a 3D transformation, using a 4x4 matrix of 16 values
translate(x, y) a 2D translation
translate3d(x, y, z) a 3D translation
translateX(x) a translation, using only the value for the X-axis
translateY(y) a translation, using only the value for the Y-axis
translateZ(z) a 3D translation, using only the value for the Z-axis
scale(x, y) a 2D scale transformation
scale3d(x, y, z) a 3D scale transformation
scaleX(x) a scale transformation by giving a value for the X-axis
scaleY(y) a scale transformation by giving a value for the Y-axis
scaleZ(z) a 3D scale transformation by giving a value for the Z-axis
rotate(angle) a 2D rotation, the angle is specified in the parameter
rotate3d(x, y, z, angle) a 3D rotation
rotateX(angle) a 3D rotation along the X-axis
rotateY(angle) a 3D rotation along the Y-axis
rotateZ(angle) a 3D rotation along the Z-axis
skew(x-angle, y-angle) a 2D skew transformation along the X- and the Y-axis
skewX(angle) a 2D skew transformation along the X-axis
skewY(angle) a 2D skew transformation along the Y-axis
perspective(n) a perspective view for a 3D transformed element
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transform property of an element.

DOM Style transformOrigin Property

Example

Set a rotated element's base placement: document.getElementById("myDIV").style.transformOrigin = "0 0";
Open in separate window
<html> <head> <style> #DIV1 {<!-- w w w . d e m o 2 s . c o m --> height: 200px; width: 200px; margin: auto; border: 1px solid black; } #DIV2 { width: 150px; height: 150px; border: 1px solid black; background-color: coral; -ms-transform: rotate(45deg); /* IE 9 */ transform: rotate(45deg); } #DIV2original { position: absolute; width: 150px; height: 150px; border: 1px dashed grey; background-color: lightgrey; opacity: 0.5; } </style> </head> <body> <p>Click the "Test" button to set the origin of the rotation to 0 for both the x-axis and the y-axis:</p> <p>The grey DIV element indicates where the DIV2 element would be without the transformation.</p> <button onclick="myFunction()">Test</button> <div id="DIV1">DIV1 <div id="DIV2original">DIV2</div> <div id="DIV2">DIV2</div> </div> <script> function myFunction() { // Code for IE9 document.getElementById("DIV2").style.msTransformOrigin = "0 0"; // Standard syntax document.getElementById("DIV2").style.transformOrigin = "0 0"; } </script> </body> </html>

Description

The transformOrigin property allows you to change the position on transformed elements. 2D transformed element can change the x- and y-axis of the element. 3D transformed element can also change the z-axis of the element. This property must be used together with the transform property.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transformOrigin Yes Yes Yes Yes Yes Yes

Syntax

Return the transformOrigin property: let a = object.style.transformOrigin; Set the transformOrigin property: object.style.transformOrigin= "x-axis y-axis z-axis|initial|inherit"

Property Values

Value Description
x-axis



Defining where the view is placed at the x-axis.
Possible values:
"left"
"center"
"right"
length in number
%
y-axis



Defining where the view is placed at the y-axis.
Possible values:
"top"
"center"
"bottom"
length in number
%
z-axis Defining where the view is placed at the z-axis (for 3D transforms).
Possible values: length
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transform-origin property of an element.

DOM Style transformStyle Property

Example

Let the transformed child elements preserve the 3D transformations: document.getElementById("myDIV").style.transformStyle = "preserve-3d";
Open in separate window
<html> <head> <style> #DIV1 {<!-- w w w . d e m o 2 s . c o m --> position: relative; height: 200px; width: 200px; margin: 100px; padding: 10px; border: 1px solid black; } #DIV2 { padding: 50px; position: absolute; border: 1px solid black; background-color: red; transform: rotateY(50deg); } #DIV3 { padding: 40px; position: absolute; border: 1px solid black; background-color: blue; transform: rotateY(70deg); } </style> </head> <body> <p>Click the "Test" button to preserve the 3D position of the child elements of the DIV2 element:</p> <button onclick="myFunction()">Test</button> <div id="DIV1">DIV1 <div id="DIV2">HELLO DIV2 <div id="DIV3">HELLO DIV3</div> </div> </div> <script> function myFunction() { document.getElementById("DIV2").style.transformStyle = "preserve-3d"; } </script> </body> </html>

Description

The transformStyle property sets or returned how nested elements are rendered in 3D space. This property must be used together with the transform property.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transformStyle Yes Yes Yes Yes Yes Yes

Syntax

Return the transformStyle property: let a = object.style.transformStyle; Set the transformStyle property: object.style.transformStyle = "flat|preserve-3d|initial|inherit"

Property Values

Value Description
flat Default value.
The child elements will NOT preserve its 3D position
preserve-3d The child elements will preserve its 3D position
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transform-style property of an element.

DOM Style transition Property

Example

Hover over a div element to gradually change its appearance: document.getElementById("myDIV").style.transition = "all 2s";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w .d em o 2 s . c o m--> border: 1px solid black; background-color: lightblue; width: 270px; height: 200px; overflow: auto; } #myDIV:hover { background-color: coral; width: 570px; height: 500px; padding: 100px; border-radius: 50px; } </style> </head> <body> <p>Mouse over the DIV element and it will change, both in color and size!</p> <p>Click the "Test" button and mouse over the DIV element again. The change will now happen gradually, like an animation:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.transition = "all 2s"; } </script> </body> </html>

Description

The transition property is a shorthand property for the four transition properties: transitionProperty, transitionDuration, transitionTimingFunction, transitionDelay. Always specify the transitionDuration property, otherwise the duration is 0, and the transition will have no effect.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transition Yes Yes Yes Yes Yes Yes

Syntax

Return the transition property: let a = object.style.transition; Set the transition property: object.style.transition= "property duration timing-function delay| initial| inherit"

Property Values

Value Description
transitionProperty the name of CSS property the transition effect is for
transitionDuration how many seconds(s) or milliseconds(ms) the transition effect takes to complete
transitionTimingFunction the speed curve of the transition effect
transitionDelay when the transition effect will start
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transition property of an element.

DOM Style transitionDelay Property

Example

Wait 2 seconds before the transition effect starts: document.getElementById("myDIV").style.transitionDelay = "2s";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d em o 2 s . c o m--> border: 1px solid black; background-color: lightblue; width: 270px; height: 200px; overflow: auto; transition: all 2s; } #myDIV:hover { background-color: coral; width: 570px; height: 500px; padding: 100px; border-radius: 50px; } </style> </head> <body> <p>Mouse over the DIV element and it will change, both in color and size!</p> <p>Click the "Test" button and mouse over the DIV element again. The changes will now wait 2 seconds before happening:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.transitionDelay = "2s"; } </script> </body> </html>

Description

The transitionDelay property sets when the transition effect will start. The transitionDelay value is defined in seconds (s) or milliseconds (ms).

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transitionDelay Yes Yes Yes Yes Yes Yes

Syntax

Return the transitionDelay property: let a = object.style.transitionDelay; Set the transitionDelay property: object.style.transitionDelay= "time|initial|inherit"

Property Values

Value Description
time the number of seconds or milliseconds to wait before the transition effect will start
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transition-delay property of an element.

DOM Style transitionDuration Property

Example

Speed up the transition effect: document.getElementById("myDIV").style.transitionDuration = "1s";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2 s. c o m --> border: 1px solid black; background-color: lightblue; width: 270px; height: 200px; overflow: auto; transition: all 5s; } #myDIV:hover { background-color: coral; width: 570px; height: 500px; padding: 100px; border-radius: 50px; } </style> </head> <body> <p>Mouse over the DIV element and it will change, both in color and size!</p> <p>Click the "Test" button and mouse over the DIV element again. The changes will now happen much faster!</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.transitionDuration = "1s"; } </script> </body> </html>

Description

The transitionDuration property gets and sets how many seconds (s) or milliseconds (ms) a transition effect takes to complete.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transitionDuration Yes Yes Yes Yes Yes Yes

Syntax

Return the transitionDuration property: let a = object.style.transitionDuration; Set the transitionDuration property: object.style.transitionDuration= "time|initial|inherit"

Property Values

Value Description
time how many seconds or milliseconds a transition effect takes to complete.
Default value is 0, meaning there will be no effect
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transition-duration property of an element.

DOM Style transitionProperty Property

Example

Hover over a div element to gradually change its width and height: document.getElementById("myDIV").style.transitionProperty = "width,height";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w. d e m o 2s .c o m --> border: 1px solid black; background-color: lightblue; width: 270px; height: 200px; overflow: auto; transition: all 2s; } #myDIV:hover { background-color: coral; width: 570px; height: 500px; padding: 100px; border-radius: 50px; } </style> </head> <body> <p>Mouse over the DIV element and it will change, gradually, both in color and size!</p> <p>Click the "Test" button and mouse over the DIV element again. The changes will still happen, but only the width and height will change gradually.</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.transitionProperty = "width, height"; } </script> </body> </html>

Description

The transitionProperty property sets the name of the CSS property the transition effect is for. The transition effect will start when the specified CSS property changes. A transition effect could typically occur when a user hover over an element. We should always specify the transitionDuration property, otherwise the duration is 0, and the transition will have no effect.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transitionProperty Yes Yes Yes Yes Yes Yes

Syntax

Return the transitionProperty property: let a = object.style.transitionProperty; Set the transitionProperty property: object.style.transitionProperty = "none|all|property|initial|inherit"

Property Values

Parameter Description
none No property will get a transition effect
all Default value.
All properties will get a transition effect
property a comma separated list of CSS property names the transition effect is for
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transition-property property of an element.

DOM Style transitionTimingFunction Property

Example

Change the speed curve of a transition effect: document.getElementById("myDIV").style.transitionTimingFunction = "linear";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2s . co m--> border: 1px solid black; background-color: lightblue; width: 270px; height: 200px; overflow: auto; transition: all 2s; } #myDIV:hover { background-color: coral; width: 570px; height: 500px; padding: 100px; border-radius: 50px; } </style> </head> <body> <p>Mouse over the DIV element and it will change, gradually, both in color and size!</p> <p>Click the "Test" button and mouse over the DIV element again. The changes will now happen in a linear speed curve.</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.transitionTimingFunction = "linear"; } </script> </body> </html>

Description

The transitionTimingFunction property specifies the speed curve of the transition effect. This property allows a transition effect to change speed over its duration.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
transitionTimingFunction Yes Yes Yes Yes Yes Yes

Syntax

Return the transitionTimingFunction property: let a = object.style.transitionTimingFunction; Set the transitionTimingFunction property: object.style.transitionTimingFunction = "ease| linear| ease-in| ease-out| ease-in-out| cubic-bezier()| initial| inherit"

Property Values

Value Description
ease Default value.
a transition effect with a slow start, then fast, then end slowly
equivalent to cubic-bezier(0.25, 0.1, 0.25, 1)
linear a transition effect with the same speed from start to end
equivalent to cubic-bezier(0, 0, 1, 1)
ease-in a transition effect with a slow start
equivalent to cubic-bezier(0.42, 0, 1, 1)
ease-out a transition effect with a slow end
equivalent to cubic-bezier(0, 0, 0.58, 1)
ease-in-out a transition effect with a slow start and end
equivalent to cubic-bezier(0.42, 0, 0.58, 1)
cubic-bezier(n, n, n, n) Define your own values in the cubic-bezier function.
Possible values are numeric values from 0 to 1
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the transition-timing-function property of an element.

DOM Style unicodeBidi Property

Example

Override text in a <p> element: document.getElementById("myP").style.unicodeBidi = "bidi-override";
Open in separate window
<html> <body> <p>This is a paragraph.</p> <p id="myP" style="direction:rtl">This is another paragraph.</p> <button type="button" onclick="myFunction()">Override text</button> <script> function myFunction() { document.getElementById("myP").style.unicodeBidi = "bidi-override"; } </script> </body> </html>

Description

The unicodeBidi property is used with the direction property to set or get whether the text should be overridden to support multiple languages in the same document.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
unicodeBidi Yes Yes Yes Yes Yes Yes

Syntax

Return the unicodeBidi property: let a = object.style.unicodeBidi; Set the unicodeBidi property: object.style.unicodeBidi = "normal| embed| bidi-override| initial| inherit"

Property Values

Value Description
normal Does not use an additional level of embedding.
This is default
embed Creates an additional level of embedding
bidi-override Creates an additional level of embedding.
Reordering depends on the direction property
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the level of embedding with respect to the bidirectional algorithm.

More Examples

Return the unicodeBidi property: console.log(document.getElementById("myP").style.unicodeBidi);
Open in separate window
<html> <body> <p>This is a paragraph.</p> <p id="myP" style="direction:rtl;unicode-bidi:bidi-override;"> This is another paragraph.</p> <button type="button" onclick="myFunction()"> Return the unicodeBidi property</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myP").style.unicodeBidi; } </script> </body> </html>

DOM Style userSelect Property

Example

Prevent text selection of a <div> element: document.getElementById("myDiv").style.userSelect = "none";
Open in separate window
<html> <body> <p>Click the "Test" button to set the user-select property of the p element to "none":</p> <button onclick="myFunction()">Test</button> <p id="demo">After you click on the button, it is not possible to select the text of this p element.</p> <script> function myFunction() {<!-- w ww . d e m o 2 s. c o m --> let x = document.getElementById("demo"); x.style.WebkitUserSelect = "none"; // Safari x.style.msUserSelect = "none"; // IE 10 and IE11 x.style.userSelect = "none"; // Standard syntax } </script> </body> </html>

Description

The userSelect property gets and sets whether the text of an element can be selected or not. If you double-click on some text, it will be selected/highlighted. This property can be used to prevent this.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
userSelect Yes Yes Yes Yes Yes Yes

Syntax

Return the userSelect property: object.style.userSelect Set the userSelect property: object.style.userSelect = "auto|none|text|all"

Property Values

Parameter Description
auto Default.
Text can be selected according to the browser's default settings
none Prevent text selection
text The text can be selected by the user
all Text selection is made with one click instead of a double-click

Default Value

Return Value

A String, representing whether the text of an element can be selected.

More Examples

Get the value of the "user-select" property of an element: document.getElementById("demo").style.userSelect;
Open in separate window
<html> <body> <p>Click the button to get the value of the "user-select" property of the p element below.</p> <button onclick="myFunction()">Test</button> <p id="demo" style="user-select:none"> It is not possible to select this text.</p> <p id='demo'></p> <script> function myFunction() {<!-- w ww . d em o 2 s . c o m --> document.getElementById('demo').innerHTML = document.getElementById("demo").style.userSelect; } </script> </body> </html>

DOM Style verticalAlign Property

Example

Set the vertical alignment of some text in a table to "bottom": document.getElementById("myTd").style.verticalAlign = "bottom";
Open in separate window
<html> <head> <style> table {<!-- w ww . d e mo 2 s . c o m --> border: 1px solid black; height: 100px; } </style> </head> <body> <table> <tr> <td id="myTd">Some example text</td> </tr> </table> <br> <button type="button" onclick="myFunction()">Align text</button> <script> function myFunction() { document.getElementById("myTd").style.verticalAlign="bottom"; } </script> </body> </html>

Description

The verticalAlign property gets and sets the vertical alignment of the content in an element.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
verticalAlign Yes Yes Yes Yes Yes Yes

Syntax

Return the verticalAlign property: let a = object.style.verticalAlign; Set the verticalAlign property: object.style.verticalAlign = value

Property Values

Value Description
length Raises or lower an element by the specified length.
Negative values are allowed
% Raises or lower an element in a percent of the "line-height" property.
Negative values are allowed
baseline Align the baseline of the element with the baseline of the parent element.
This is default
sub Aligns the element as it was subscript
super Aligns the element as it was superscript
top The top of the element is aligned with the top of the tallest element on the line
text-top The top of the element is aligned with the top of the parent element's font
middle The element is placed in the middle of the parent element
bottom The bottom of the element is aligned with the lowest element on the line
text-bottom The bottom of the element is aligned with the bottom of the parent element's font
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the vertical alignment of the content in an element.

More Examples

Return the vertical alignment of a <td> element: console.log(document.getElementById("myTd").style.verticalAlign);
Open in separate window
<html> <head> <style> table {<!-- w w w. d e m o2 s .c o m --> border: 1px solid black; height: 100px; } </style> </head> <body> <table> <tr> <td id="myTd" style="vertical-align:top;">Some example text</td> </tr> </table> <br> <button type="button" onclick="myFunction()"> Return vertical alignment</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myTd").style.verticalAlign; } </script> </body> </html>

DOM Style visibility Property

Example

Hide the content of a <p> element: document.getElementById("myP").style.visibility = "hidden";
Open in separate window
<html> <body> <p id="myP">This is a p element.</p> <button type="button" onclick="myFunction()">Hide content of p</button> <script> function myFunction() { document.getElementById("myP").style.visibility = "hidden"; } </script> </body> </html>

Description

The visibility property gets and sets whether an element should be visible. The visibility property allows the author to show or hide an element. It is similar to the display property. Setting display:none hides the entire element and removes it from layout, while visibility:hidden hides the element, but the element stays in its original position and size.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
visibility Yes Yes Yes Yes Yes Yes

Syntax

Return the visibility property: let a = object.style.visibility; Set the visibility property: object.style.visibility = "visible|hidden|collapse|initial|inherit"

Property Values

Parameter Description
visible The element is visible.
This is default
hidden The element is not visible, but still affects layout
collapse When used on a table row or cell, the element is not visible
same as "hidden"
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing whether the content of an element is displayed or not.

More Examples

Difference between the display property and the visibility property: function demoDisplay() { document.getElementById("myP1").style.display = "none"; } function demoVisibility() { document.getElementById("myP2").style.visibility = "hidden"; }
Open in separate window
<html> <body> <p id="myP1">This is some text.</p> <p id="myP2">This is some text.</p> <input type="button" onclick="demoDisplay()" value="Hide text with display property"> <input type="button" onclick="demoVisibility()" value="Hide text with visibility property"> <script> function demoDisplay() {<!-- w w w. d e m o 2 s . co m --> document.getElementById("myP1").style.display = "none"; } function demoVisibility() { document.getElementById("myP2").style.visibility = "hidden"; } </script> </body> </html>

Example

Toggle between hiding and showing an element: function myFunction() { let x = document.getElementById('myDIV'); if (x.style.visibility === 'hidden') { x.style.visibility = 'visible'; } else { x.style.visibility = 'hidden'; } }
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2 s. c o m --> width: 500px; height: 500px; background-color: lightblue; } </style> </head> <body> <p>Click the "Test" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> This is my DIV element. </div> <p>Note that even though the element is hidden, it stays in its original position and size.</p> <script> function myFunction() { let x = document.getElementById('myDIV'); if (x.style.visibility === 'hidden') { x.style.visibility = 'visible'; } else { x.style.visibility = 'hidden'; } } </script> </body> </html>

Example

Hide and show an <img> element: function hideElem() { document.getElementById("myImg").style.visibility = "hidden"; } function showElem() { document.getElementById("myImg").style.visibility = "visible"; }
Open in separate window
<html> <body> <img id="myImg" src="css.png" width="100" height="132"> <br> <button type="button" onclick="hideElem()">Hide image</button> <button type="button" onclick="showElem()">Show image</button> <script> function hideElem() {<!-- w ww . d e m o 2 s . c o m --> document.getElementById("myImg").style.visibility = "hidden"; } function showElem() { document.getElementById("myImg").style.visibility = "visible"; } </script> </body> </html>

Example

Return the visibility type of a <p> element: console.log(document.getElementById("myP").style.visibility);
Open in separate window
<html> <body> <p id="myP" style="visibility:hidden;">This is a p element.</p> <button type="button" onclick="myFunction()"> Return the visibility type of p</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myP").style.visibility; } </script> </body> </html>

DOM Style whiteSpace Property

Example

Specify that the text in the <div> element will never wrap: document.getElementById("myDIV").style.whiteSpace = "nowrap";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2 s. c o m --> width: 400px; height: 200px; background-color: lightblue; border: 1px solid black; } </style> </head> <body> <p>Click the "Test" button to make sure that the text inside the DIV element never wraps:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <script> function myFunction() { document.getElementById("myDIV").style.whiteSpace = "nowrap"; } </script> </body> </html>

Description

The whiteSpace property gets and sets how to handle tabs, line breaks and whitespace in a text.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
whiteSpace Yes Yes Yes Yes Yes Yes

Syntax

Return the whiteSpace property: let a = object.style.whiteSpace; Set the whiteSpace property: object.style.whiteSpace = "normal|nowrap|pre|initial|inherit"

Property Values

Parameter Description
normal Sequences of whitespace will collapse into a single whitespace.
Text will wrap when necessary.
This is default
nowrap Sequences of whitespace will collapse into a single whitespace.
Text will not wrap to the next line.
The text continues on the same line until a <br> tag is encountered
pre Whitespace is preserved by the browser.
Text will only wrap on line breaks.
Acts like the <pre> tag in HTML
pre-line Sequences of whitespace will collapse into a single whitespace.
Text will wrap when necessary, and on line breaks
pre-wrap Whitespace is preserved by the browser.
Text will wrap when necessary, and on line breaks
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing how white-space inside an element is handled.

More Examples

Return the whiteSpace property console.log(document.getElementById("myDiv").style.whiteSpace);
Open in separate window
<html> <body> <div id="myDiv" style="white-space:nowrap;"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. </div><!-- w ww . d e m o 2 s. c o m --> <br> <button type="button" onclick="myFunction()"> Return the whiteSpace property</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myDiv").style.whiteSpace; } </script> </body> </html>

DOM Style widows Property

Example

Change the widows and check print or print preview: <html> /* w w w . d em o 2 s . c o m */ <head> <script> function ChangeWidows() { document.getElementById("p1").style.widows = document.getElementById("widows").value; } </script> <style> .othercontent { width: 400px; border-top: 19cm solid #c3c3c3; } @page { /* set size of printed page */ size: 21cm 27cm; margin-top: 2cm; } @media print { .widows { widows:2; } } </style> </head> <body> <div class="othercontent"> <input id="widows" value="2"> <button onclick="ChangeWidows();">Change widows</button> <p style="font-size:120%" id="p1"> Change widows and see the print preview. <br> Line 2 <br> Line 3 <br> Line 4 <br> Line 5 <br> Line 6 <br> Line 7 <br> Line 8 <br> </p> <div class="othercontent"> </body> </html>

Description

The widows property gets and sets the minimum number of lines for an element that must be visible at the top of a page for printing or print preview. For example, widows:5 means that at least 5 lines must be visible below the page break. The widows property only affects block-level elements. We can use the orphans property to set or get the minimum number of lines for an element that must be visible at the bottom of a page. widows is supported by chrome.

Syntax

Return the widows property: let a = object.style.widows; Set the widows property: object.style.widows = "number|initial|inherit"

Property Values

Value Description
number An integer that specifies the minimum number of visible lines.
Negative values are not allowed.
The default value is 2
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the minimum number of lines to print at the top of the page.

DOM Style width Property

Example

Set the width of a <button> element: document.getElementById("myBtn").style.width = "300px";
Open in separate window
<html> <body> <button type="button" id="myBtn" onclick="myFunction()"> Change the width of this button</button> <script> function myFunction() { document.getElementById("myBtn").style.width = "300px"; } </script> </body> </html>

Description

The width property gets and sets the width an element. The width property only controls block-level elements or on elements with absolute or fixed position. The overflowing content can be manipulated with the overflow property. We can use the height property to set or get the height of an element.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
width Yes Yes Yes Yes Yes Yes

Syntax

Return the width property: let a = object.style.width; Set the width property: object.style.width = "auto|length|%|initial|inherit"

Property Values

Value Description
auto The browser sets the width.
This is default
length Defines the width in length units
% Defines the width in % of the parent element
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the width of an element.

More Examples

Change the width of a <div> element: document.getElementById("myDIV").style.width = "500px";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w. d e m o 2 s . c o m --> width: 100px; height: 100px; background-color: coral; color: white; } </style> </head> <body> <p>Click the "Test" button to change the width of the DIV element:</p> <button onclick="myFunction()">Test</button> <div id="myDIV"> <h1>myDIV</h1> </div> <script> function myFunction() { document.getElementById("myDIV").style.width = "500px"; } </script> </body> </html>

Example

Change the height and width of an <img> element: document.getElementById("myImg").style.height = "300px"; document.getElementById("myImg").style.width = "300px";
Open in separate window
<html> <body> <img id="myImg" src="css.png" width="100" height="132"> <br> <button type="button" onclick="myFunction()"> Change height and width of image</button> <script> function myFunction() { document.getElementById("myImg").style.height = "300px"; document.getElementById("myImg").style.width = "300px"; } </script> </body> </html>

Example

Return the width of an <img> element: console.log(document.getElementById("myImg").style.width);
Open in separate window
<html> <body> <img id="myImg" src="css.png" style="width:100px;height:132px;"> <br> <button type="button" onclick="myFunction()">Return width of image</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myImg").style.width; } </script> </body> </html>

DOM Style wordBreak Property

Example

Break words between any two letters: document.getElementById("myDIV").style.wordBreak = "break-all";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w. d e m o 2s . c o m --> width: 150px; height: 100px; background-color: lightblue; border: 1px solid black; } </style> </head> <body> <p>Click the "Test" button to change the let the DIV element break a text between any two letters:</p> <div id="myDIV">111111111111111111111111111111111111111111111111111</div> <button onclick="myFunction()">Test</button> <script> function myFunction() { document.getElementById("myDIV").style.wordBreak = "break-all"; } </script> </body> </html>

Description

The wordBreak property specifies line breaking rules for non-CJK scripts. CJK scripts are Chinese, Japanese and Korean ("CJK") scripts.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
wordBreak Yes Yes Yes Yes Yes Yes

Syntax

Return the wordBreak property: let a = object.style.wordBreak; Set the wordBreak property: object.style.wordBreak = "normal|break-all|keep-all|initial|inherit"

Property Values

Value Description
normal Default value.
Break words according to their usual rules
break-all Lines may break between any two letters
keep-all Breaks are prohibited between pairs of letters
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the word-break property of an element.

DOM Style wordSpacing Property

Example

Set the space between words in a <p> element to 50 pixels: document.getElementById("myP").style.wordSpacing = "50px";
Open in separate window
<html> <body> <p id="myP">This is an example paragraph.</p> <button type="button" onclick="myFunction()"> Set word spacing</button> <script> function myFunction() { document.getElementById("myP").style.wordSpacing = "50px"; } </script> </body> </html>

Description

The wordSpacing property gets and sets the spacing between words in a text. To set or get the spacing between characters in a text, use the letterSpacing property.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
WordSpacing Yes Yes Yes Yes Yes Yes

Syntax

Return the wordSpacing property: let a = object.style.wordSpacing; Set the wordSpacing property: object.style.wordSpacing = "normal|length|initial|inherit"

Property Values

Value Description
normal Defines normal spacing between words.
This is default
length the space between words in length units.
Negative values are allowed
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the space between words in the text.

More Examples

Using negative values: document.getElementById("myP").style.wordSpacing = "-3px";
Open in separate window
<html> <body> <p id="myP">This is an example paragraph.</p> <button type="button" onclick="myFunction()">Set word spacing</button> <script> function myFunction() { document.getElementById("myP").style.wordSpacing = "-3px"; } </script> </body> </html>

Example

Return the word spacing of a <p> element: console.log(document.getElementById("myP").style.wordSpacing);
Open in separate window
<html> <body> <p id="myP" style="word-spacing:10px;">This is an example paragraph.</p> <button type="button" onclick="myFunction()">Return word spacing of p</button> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("myP").style.wordSpacing; } </script> </body> </html>

Example

Difference between the letterSpacing property and the wordSpacing property: function changeLetters() { document.getElementById("demo1").style.letterSpacing = "15px"; } function changeWords() { document.getElementById("demo2").style.wordSpacing = "15px"; }
Open in separate window
<html> <body> <p id="demo1">This is an example paragraph.</p> <p id="demo2">This is an example paragraph.</p> <button type="button" onclick="changeLetters()">Set letter spacing</button> <button type="button" onclick="changeWords()">Set word spacing</button> <script> function changeLetters() {<!-- ww w . d e m o 2 s .c o m--> document.getElementById("demo1").style.letterSpacing = "15px"; } function changeWords() { document.getElementById("demo2").style.wordSpacing = "15px"; } </script> </body> </html>

DOM Style wordWrap Property

Example

Allow long words to be able to break and wrap onto the next line: document.getElementById("myDIV").style.wordWrap = "break-word";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d e m o 2s . c o m --> width: 150px; height: 100px; background-color: lightblue; border: 1px solid black; } </style> </head> <body> <p>Click the "Test" button to change the let the DIV element wrap words:</p> <div id="myDIV">111111111111111111111111111111111111111111111</div> <button onclick="myFunction()">Test</button> <script> function myFunction() { document.getElementById("myDIV").style.wordWrap = "break-word"; } </script> </body> </html>

Description

The wordWrap property allows long words to be able to be broken and wrap onto the next line.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
wordWrap Yes Yes Yes Yes Yes Yes

Syntax

Return the wordWrap property: let a = object.style.wordWrap; Set the wordWrap property: object.style.wordWrap = "normal|break-word|initial|inherit"

Property Values

Parameter Description
normal Break words only at allowed break points
break-word Allows unbreakable words to be broken
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the word-wrap property of an element.

DOM Style zIndex Property

Example

Change the stack order of an <img> element: document.getElementById("img1").style.zIndex = "1";
Open in separate window
<html> <head> <style> #img1 {<!-- w w w .d e m o 2s . c o m --> position: absolute; left: 0px; top: 0px; z-index: -1 } </style> </head> <body> <h1>This is a Heading</h1> <img id="img1" src="css.png" width="100" height="180"> <button type="button" onclick="myFunction()">Change stack order</button> <p>Default z-index is 0. Z-index -1 has lower priority.</p> <script> function myFunction() { document.getElementById("img1").style.zIndex = "1"; } </script> </body> </html>

Description

The zIndex property gets and sets the stack order of a positioned element. An element with greater stack order is always in front of another element with lower stack order. A positioned element is an element with the position property set to: relative, absolute, or fixed. This property is useful to create overlapping elements.

Browser Compatibility

Chrome.png Node.png Firefox.png Safari.png Edge.png Opera.png
zIndex Yes Yes Yes Yes Yes Yes

Syntax

Return the zIndex property: let a = object.style.zIndex; Set the zIndex property: object.style.zIndex = "auto|number|initial|inherit"

Property Values

Value Description
auto sets the stack order of the element based on its order in the document.
This is default
number An integer that defines the stack order of the element.
Negative values are allowed
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Default Value

Return Value

A String, representing the stack order of an element.

More Examples

Change the z-index property value of an <div> element: document.getElementById("myDIV").style.zIndex = "-1";
Open in separate window
<html> <head> <style> #myDIV {<!-- w w w . d em o 2 s . c o m --> position: absolute; width: 300px; height: 150px; background-color: lightblue; border: 1px solid black; } #DIV2 { position: relative; top: 130px; left: 30px; width: 300px; height: 150px; background-color: coral; border: 1px solid black; } </style> </head> <body> <p>Click the "Test" button to change the z-index of the blue DIV element:</p> <button onclick="myFunction()">Test</button> <div id="DIV2"> <h1>Voila!</h1> </div> <div id="myDIV"> </div> <script> function myFunction() { document.getElementById("myDIV").style.zIndex = "-1"; } </script> </body> </html>

Example

Return the z-index property value of an <img> element: console.log(document.getElementById("img1").style.zIndex);
Open in separate window
<html> <body> <h1>This is a Heading</h1> <img id="img1" src="css.png" style=<!-- w ww . d e mo 2 s . c o m --> "position:absolute;left:0px;top:0px;z-index:-1;width:100px;height:180px;"> <button type="button" onclick="myFunction()">Alert stack order</button> <p>Default z-index is 0. Z-index -1 has lower priority.</p> <p id='demo'></p> <script> function myFunction() { document.getElementById('demo').innerHTML = document.getElementById("img1").style.zIndex; } </script> </body> </html>

DOM Form Scripting Introduction

Web forms are represented by the <form> element in HTML and by the HTMLFormElement type in JavaScript. The HTMLFormElement type inherits from HTMLElement and therefore has all of the same default properties as other HTML elements. However, HTMLFormElement also has the following additional properties and methods:
Property Meaning
acceptCharset The character sets that the server can process;
equivalent to the HTML accept-charset attribute.
action The URL to send the request to;
equivalent to the HTML action attribute.
elements An HTMLCollection of all controls in the form.
enctype The encoding type of the request;
equivalent to the HTML enctype attribute.
length The number of controls in the form.
method The type of HTTP request to send, typically "get" or "post";
equivalent to the HTML method attribute.
name The name of the form; equivalent to the HTML name attribute.
reset() Resets all form fields to their default values.
submit() Submits the form.
target The name of the window to use for sending the request and receiving the response;
equivalent to the HTML target attribute.
We can get form element by the id attribute getElementById(), as in the following example: let form = document.getElementById("form1"); All forms on the page can also be retrieved from document.forms collection. Each form can be accessed in this collection by numeric index and by name, as shown in the following examples: // get the first form in the page let firstForm = document.forms[0]; // get the form with a name of "form2" let myForm = document.forms["form2"]; The forms can have both an id and a name and that these values need not be the same.

DOM Submitting Forms

Forms are submitted when a user interacts with a submit button or an image button. Submit buttons are defined using either the <input> element or the <button> element with a type attribute of "submit", and image buttons are defined using the <input> element with a type attribute of "image". All of the following, when clicked, will submit a form in which the button resides: generic submit button. <input type="submit" value="Submit Form"> custom submit button. <button type="submit">Submit Form</button> image button. <input type="image" src="graphic.gif"> If any one of these types of buttons is within a form that has a submit button, pressing Enter on the keyboard while a form control has focus will also submit the form. The forms without a submit button will not be submitted when Enter is pressed. When a form is submitted in this manner, the submit event fires right before the request is sent to the server. We can validate the form data and decide whether to allow the form submission to occur. Preventing the event's default behavior cancels the form submission. For example, the following prevents a form from being submitted: let form = document.getElementById("myForm"); form.addEventListener("submit", (event) => { // prevent form submission event.preventDefault(); }); The preventDefault() method stops the form from being submitted. Typically, this functionality is used when data in the form is invalid and should not be sent to the server. We can submit a form programmatically by calling the submit() method from JavaScript. This method can be called at any time to submit a form and does not require a submit button to be present in the form to function appropriately. Here's an example: let form = document.getElementById("myForm"); // submit the form form.submit(); When a form is submitted via submit(), the submit event does not fire, so be sure to do data validation before calling the method. To stop submitting the form twice, we can disable the submit button once the form is submitted, or use the onsubmit event handler to cancel any further form submissions.

DOM Resetting Forms

Forms are reset when the user clicks a reset button. Reset buttons are created using either the <input> or the <button> element with a type attribute of "reset", as in these examples: generic reset button. <input type="reset" value="Reset Form"> custom reset button. <button type="reset">Reset Form</button> Either of these buttons will reset a form. When a form is reset, all of the form fields are set back to the values they had when the page was first rendered. If a field was originally blank, it becomes blank again, whereas a field with a default value reverts to that value. When a form is reset by the user clicking a reset button, the reset event fires. This event gives you the opportunity to cancel the reset if necessary. For example, the following prevents a form from being reset: let form = document.getElementById("myForm"); form.addEventListener("reset", (event) => { event.preventDefault(); }); Resetting a form can be accomplished via JavaScript using the reset() method, as in this example: let form = document.getElementById("myForm"); // reset the form form.reset(); reset() method fires the reset event the same as if a reset button were clicked.

DOM Form Automatic Tab Forward

We can use Javascript to automatically move the focus to the next field when the current field is complete. This is frequently done when entering data whose appropriate length is already known, such as for telephone numbers. In the United States, telephone numbers are typically split into three parts: the area code, the exchange, and then four more digits. It's quite common for web pages to represent this as three text boxes, such as the following: <input type="text" name="tel1" id="txtTel1" maxlength="3"> <input type="text" name="tel2" id="txtTel2" maxlength="3"> <input type="text" name="tel3" id="txtTel3" maxlength="4"> To aid in usability and speed up the data-entry process, you can automatically move focus to the next element as soon as the maximum number of characters has been entered. So once the user types three characters in the first text box, the focus moves to the second, and once the user types three characters in the second text box, the focus moves to the third. This "tab forward" behavior can be accomplished using the following code: <script>/*w w w .d e m o 2s . c om */ function tabForward(event){ let target = event.target; if (target.value.length == target.maxLength){ let form = target.form; for (let i = 0, len = form.elements.length; i < len; i++) { if (form.elements[i] == target) { if (form.elements[i+1]) { form.elements[i+1].focus(); } return; } } } } let inputIds = ["txtTel1", "txtTel2", "txtTel3"]; for (let id of inputIds) { let textbox = document.getElementById(id); textbox.addEventListener("keyup", tabForward); } let textbox1 = document.getElementById("txtTel1"); let textbox2 = document.getElementById("txtTel2"); let textbox3 = document.getElementById("txtTel3"); </script> The tabForward() function checks to see if the text box's maximum length has been reached by comparing the value to the maxlength attribute. If they're equal, then the next form element needs to be found by looping through the elements collection until the text box is found and then setting focus to the element in the next position. This function is then assigned as the onkeyup handler for each text box. Since the keyup event fires after a new character has been inserted into the text box, this is the ideal time to check the length of the text box contents. When filling out this simple form, the user will never have to press the Tab key to move between fields and submit the form.

DOM Form Fields

Form elements can be accessed using DOM methods. All form elements are parts of an elements collection that is a property of each form. The elements collection is an ordered list of references to all form fields in the form and includes all <input>, <textarea>, <button>, <select>, and <fieldset> elements. Each form field appears in the elements collection in the order in which it appears in the markup, indexed by both position and name. Here are some examples: let form = document.getElementById("form1"); get the first field in the form. let field1 = form.elements[0]; get the field named textbox1. let field2 = form.elements["textbox1"]; get the number of fields. let fieldCount = form.elements.length; If a name is in use by multiple form controls, as is the case with radio buttons, then an HTMLCollection is returned containing all of the elements with the name. For example, consider the following HTML snippet: <form method="post" id="myForm"> <ul> <li><input type="radio" name="color" value="red">Red</li> <li><input type="radio" name="color" value="green">Green</li> <li><input type="radio" name="color" value="blue">Blue</li> </ul> </form> The form in this HTML has three radio controls that have "color" as their name, which ties the fields together. When accessing elements["color"], a NodeList is returned, containing all three elements; when accessing elements[0], however, only the first element is returned. Consider this example: let form = document.getElementById("myForm"); let colorFields = form.elements["color"]; console.log(colorFields.length); // 3 let firstColorField = colorFields[0]; let firstFormField = form.elements[0]; console.log(firstColorField === firstFormField); // true This code shows that the first form field, accessed via form.elements[0], is the same as the first element contained in form.elements["color"]. We can access elements as properties of a form as well, such as form[0] to get the first form field and form["color"] to get a named field. These properties always return the same thing as their equivalent in the elements collection.

DOM Common Form-Field Properties

With the exception of the <fieldset> element, all form fields share a common set of properties. Because the <input> type represents many form fields, some properties are used only with certain field types, whereas others are used regardless of the field type. The common form-field properties and methods are as follows:
Property Meaning
disabled A Boolean indicating if the field is disabled.
form A pointer to the form that the field belongs to.
This property is read-only.
name The name of the field.
readOnly A Boolean indicating if the field is read-only.
tabIndex Indicates the tab order for the field.
type The type of the field: "checkbox", "radio", and so on.
value The value of the field that will be submitted to the server.
For file-input fields, this property is read only and simply contains the file's path on the computer.
With the exception of the form property, JavaScript can change all other properties dynamically. Consider this example: let form = document.getElementById("myForm"); let field = form.elements[0]; change the value. field.value = "Another value"; check the value of form. console.log(field.form === form); // true set focus to the field. field.focus(); disable the field. field.disabled = true; change the type of field (not recommended, but possible for <input>). field.type = "checkbox"; The ability to change form-field properties dynamically allows you to change the form at any time and in almost any way.

Example

We can prevent users from clicking the submit button twice by disabling the submit button once it's been clicked. We can listen for the submit event and disabling the submit button when it occurs. The following code accomplishes this: // Code to prevent multiple form submissions let form = document.getElementById("myForm"); form.addEventListener("submit", (event) => { let target = event.target; // get the submit button let btn = target.elements["submit-btn"]; // disable the submit button btn.disabled = true; }); This code attaches an event handler on the form for the submit event. When the event fires, the submit button is retrieved and its disabled property is set to true. You cannot attach an onclick event handler to the submit button to do this because of a timing issue across browsers: some browsers fire the click event before the form's submit event, some after. Therefore it's better to disable the submit button using the submit event. This approach won't work if you are submitting the form without using a submit button because, the submit event is fired only by a submit button.

Type

The type property exists for all form fields except <fieldset>. For <input> elements, this value is equal to the HTML type attribute. For other elements, the value of type is set as described in the following table.
Description Sample Html Value Of Type
Single-select list <select>...</select> "select-one"
Multi-select list <select multiple>...</select> "select-multiple"
Custom button <button>...</button> "submit"
Custom non submit button <button type="button">...</button> "button"
Custom reset button <button type="reset">...</button> "reset"
Custom submit button <button type="submit">...</button> "submit"
For <input> and <button> elements, the type property can be changed dynamically, whereas the <select> element's type property is read-only.

DOM Common Form-Field Methods

Each form field has two methods in common: focus() and blur(). The focus() method sets the browser's focus to the form field, meaning that the field becomes active and will respond to keyboard events. For example, a text box that receives focus displays its caret and is ready to accept input. The focus() method is most often used to get the user's attention to some part of the page. We can move the focus to the first field in a form when the page is loaded. This can be accomplished by listening for the load event and then calling focus() on the first field, as in the following example: window.addEventListener("load", (event) => { document.forms[0].elements[0].focus(); }); This code will cause an error if the first form field is an <input> element with a type of "hidden" or if the field is being hidden using the display or visibility CSS property. HTML5 introduces an autofocus attribute for form fields that causes supporting browsers to automatically set the focus to that element without the use of JavaScript. For example: <input type="text" autofocus> In order for the previous code to work correctly with autofocus, you must first detect if it has been set. window.addEventListener("load", (event) => { let element = document.forms[0].elements[0]; if (element.autofocus !== true) { element.focus(); console.log("JS focus"); } }); Because autofocus is a Boolean attribute, the value of the autofocus property will be true in supporting browsers. It will be the empty string in browsers without support. So this code calls focus() only if the autofocus property is not equal to true, ensuring forwards compatibility. The autofocus property is supported in most modern browsers. By default, only form elements can have focus set to them. It's possible to allow any element to have focus by setting its tabIndex property to -1 and then calling focus().

Blur

The opposite of focus() is blur(), which removes focus from the element. When blur() is called, focus isn't moved to any element in particular; it's just removed from the field on which it was called. Here's an example: document.forms[0].elements[0].blur();

DOM Common Form-Field Events

All form fields support the following three events in addition to mouse, keyboard, mutation, and HTML events:
Event Meaning
blur Fires when the field loses focus.
change Fires when the field loses focus and the value has changed for <input> and <textarea> elements;
Fires when the selected option changes for <select> elements.
focus Fires when the field gets focus.
Both the blur and the focus events fire because of users manually changing the field's focus, as well as by calling the blur() and focus() methods, respectively. These two events work the same way for all form fields. The change event, however, fires at different times for different controls. For <input> and <textarea> elements, the change event fires when the field loses focus and the value has changed since the time the control got focus. For <select> elements, however, the change event fires whenever the user changes the selected option; the control need not lose focus for change to fire. The focus and blur events are typically used to change the user interface in some way, to provide either visual cues or additional functionality, such as showing a drop-down menu of options for a text box. The change event is typically used to validate data that was entered into a field.

Example

For example, for a number only text box, the focus event may be used to change the background color to more clearly indicate that the field has focus, the blur event can be used to remove that background color, and the change event can change the background color to red if non numeric characters are entered. The following code accomplishes this: let textbox = document.forms[0].elements[0]; textbox.addEventListener("focus", (event) => { let target = event.target; if (target.style.backgroundColor != "red") { target.style.backgroundColor = "yellow"; } }); textbox.addEventListener("blur", (event) => { let target = event.target; target.style.backgroundColor = /[^\d]/.test(target.value) ? "red" : ""; }); textbox.addEventListener("change", (event) => { let target = event.target; target.style.backgroundColor = /[^\d]/.test(target.value) ? "red" : ""; }); The onfocus event handler simply changes the background color of the text box to yellow, more clearly indicating that it's the active field. The onblur and onchange event handlers turn the background color red if any non numeric character is found. To test for a non numeric character, use a simple regular expression against the text box's value. This functionality has to be in both the onblur and onchange event handlers to ensure that the behavior remains consistent regardless of text box changes. In some browsers, the blur event fires before change event; in others, it's the opposite.

DOM Scripting Text Boxes

There are two ways to represent text boxes in HTML: a single-line version using the <input> element a multiline version using <textarea>. These two controls are very similar and behave in similar ways most of the time. By default, the <input> element displays a text box, even when the type attribute is omitted. The default value is "text". The size attribute can then be used to specify how wide the text box should be in terms of visible characters. The value attribute specifies the initial value of the text box, and the maxlength attribute specifies the maximum number of characters allowed in the text box. To create a text box that can display 25 characters but has a maximum length of 50, you can use the following code: <input type="text" size="25" maxlength="50" value="initial value">

textarea

The <textarea> element always renders a multiline text box. To specify how large the text box should be, you can use the rows attribute, which specifies the height of the text box in number of characters, and the cols attribute, which specifies the width in number of characters, similar to size for an <input> element. The initial value of a <textarea> must be enclosed between <textarea> and </textarea>, as shown here: <textarea rows="25" cols="5">initial value</textarea> A <textarea> cannot specify the maximum number of characters allowed using HTML. Both types of text boxes store their contents in the value property. The value can be used to read the text box value and to set the text box value, as in this example: let textbox = document.forms[0].elements["textbox1"]; console.log(textbox.value); textbox.value = "Some new value"; You should use the value property to read or write text box values rather than to use standard DOM methods. Fon't use setAttribute() to set the value attribute on an <input> element, and don't try to modify the first child node of a <textarea> element. Changes to the value property aren't always reflected in the DOM either.

DOM Form Text Input Box Text Selection

Both types of text boxes in the form support a method called select(), which selects all of the text in a text box. Most browsers automatically set focus to the text box when the select() method is called. The method accepts no arguments and can be called at any time. Here's an example: let textbox = document.forms[0].elements["textbox1"]; textbox.select(); It's quite common to select all of the text in a text box when it gets focus, especially if the text box has a default value. This pattern is accomplished with the following code: textbox.addEventListener("focus", (event) => { event.target.select(); }); With this code applied to a text box, all of the text will be selected as soon as the text box gets focus. This can greatly aid the usability of forms.

DOM Form Text box select Event

The select event from form text box fires when text is selected in the text box. Exactly when the event fires differs from browser to browser. The select event also fires when the select() method is called. Here's a simple example: let textbox = document.forms[0].elements["textbox1"]; textbox.addEventListener("select", (event) => { console.log(`Text selected: ${textbox.value}`); });

DOM Form Text Box Retrieving Selected Text

To get selected text from form text box, use selectionStart and selectionEnd properties. These properties contain zero-based numbers indicating the text-selection boundaries: the offset of the beginning of text selection and the offset of end of text selection, respectively. To get the selected text in a text box, you can use the following code: function getSelectedText(textbox){ return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd); } Because the substring() method works on string offsets, the values from selectionStart and selectionEnd can be passed in directly to retrieve the selected text.

DOM Form Text Box Partial Text Selection

HTML5 supports partially selecting text in a text box. The setSelectionRange() method available on all text boxes. This method takes two arguments: the index of the first character to select and the index at which to stop the selection. Here are some examples: textbox.value = "Hello world!" select all text. textbox.setSelectionRange(0, textbox.value.length); // "Hello world!" select first three characters. textbox.setSelectionRange(0, 3); // "Hel" select characters 4 through 6. textbox.setSelectionRange(4, 7); // "o w" To see the selection, you must set focus to the text box either immediately before or after a call to setSelectionRange().

DOM Form Text Box Blocking Characters

Certain types of input require that specific characters be present or absent. For example, a text box for the user's phone number should not allow non-numeric values to be inserted. The keypress event is responsible for inserting characters into a text box. Characters can be blocked by preventing this event's default behavior. For example, the following code blocks all key presses: textbox.addEventListener("keypress", (event) => { event.preventDefault(); }); Running this code causes the text box to effectively become read only, because all key presses are blocked. To block only specific characters, you need to inspect the character code for the event and determine the correct response. For example, the following code allows only numbers: textbox.addEventListener("keypress", (event) => { if (!/\d/.test(String.fromCharCode(event.charCode))){ event.preventDefault(); } }); In this example, the character code is converted to a string using String.fromCharCode(), and the result is tested against the regular expression /\d/, which matches all numeric characters. If that test fails, then the event is blocked using preventDefault(). This ensures that the text box ignores non-numeric keys. Even though the keypress event should be fired only when a character key is pressed, some browsers fire it for other keys as well. If you don't want to block any character codes lower than 10. The function can then be updated as follows: textbox.addEventListener("keypress", (event) => { if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9){ event.preventDefault(); } }); The event handler now behaves appropriately in all browsers, blocking non numeric characters but allowing all basic keys that also fire keypress. There is still one more issue to handle: copying, pasting, and any other functions that involve the Ctrl key. The last check is to make sure the Ctrl key is not pressed, as shown in the following example: textbox.addEventListener("keypress", (event) => { if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9 && !event.ctrlKey){ event.preventDefault(); } }); This final change ensures that all of the default text box behaviors work. This technique can be customized to allow or disallow any characters in a text box.

DOM Form Scripting Select Boxes

Select boxes are created using the <select> and <option> elements. The HTMLSelectElement type provides the following properties and methods in addition to those that are available on all form fields:
Method Meaning
add(newOption, relOption) Adds a new <option> element to the control before the related option.
multiple A Boolean value indicating if multiple selections are allowed;
equivalent to the HTML multiple attribute.
options An HTMLCollection of <option> elements in the control.
remove(index) Removes the option in the given position.
selectedIndex The zero-based index of the selected option or -1 if no options are selected.
For select boxes that allow multiple selections,
this is always the first option in the selection.
size The number of rows visible in the select box;
equivalent to the HTML size attribute.
The type property for a select box is either "select-one" or "select-multiple", depending on the absence or presence of the multiple attribute. The option that is currently selected determines a select box's value property according to the following rules: If there is no option selected, the value of a select box is an empty string. If an option is selected and it has a value attribute specified, then the select box's value is the value attribute of the selected option. This is true even if the value attribute is an empty string. If an option is selected and it doesn't have a value attribute specified, then the select box's value is the text of the option. If multiple options are selected, then the select box's value is taken from the first selected option according to the previous two rules. Consider the following select box: <select name="language" id="selLanguage"> <option value="CSS">CSS</option> <option value="HTML">HTML</option> <option value="Java">Java</option> <option value="">SQL</option> <option>Javascript</option> </select> If the first option in this select box is selected, the value of the field is "CSS Lang". If the option with the text "SQL" is selected, then the field's value is an empty string because the value attribute is empty. If the last option is selected, then the value is "Javascript" because there is no value attribute specified on the <option>. Each <option> element is represented in the DOM by an HTMLOptionElement object. The HTMLOptionElement type adds the following properties for easier data access:
Property Meaning
index The option's index inside the options collection.
label The option's label; equivalent to the HTML label attribute.
selected A Boolean value used to indicate if the option is selected.
Set this property to true to select an option.
text The option's text.
value The option's value
equivalent to the HTML value attribute.
Most of the <option> properties are used for faster access to the option data. We can use normal DOM functionality to access this information, as this example shows: let selectbox = document.forms[0].elements["language"]; let text = selectbox.options[0].firstChild.nodeValue; // option text let value = selectbox.options[0].getAttribute("value"); // option value This code gets the text and value of the first option in the select box using standard DOM techniques. We can also use the special option properties: let selectbox = document.forms[0].elements["location"]; let text = selectbox.options[0].text; // option text let value = selectbox.options[0].value; // option value When dealing with options, it's best to use the option-specific properties because they are well supported across all browsers. It is not recommended to change the text or values of <option> elements by using standard DOM techniques. There is a difference how the change event is used for select boxes. The field loses focus, the change event fires on select boxes as soon as an option is selected. The value property is always equal to the value attribute in all browsers.

DOM Form Selection Element Options Selection

To select an option from a single selection box, use the select box's selectedIndex property, as shown in the following example: let selectedOption = selectbox.options[selectbox.selectedIndex]; This can be used to display all of the information about the selected option, as in this example: let selectedIndex = selectbox.selectedIndex; let selectedOption = selectbox.options[selectedIndex]; console.log(`Selected index: $[selectedIndex}\n` + `Selected text: ${selectedOption.text}\n` + `Selected value: ${selectedOption.value}`); Here, a log message is displayed showing the selected index along with the text and value of the selected option. When used in a select box that allows multiple selections, the selectedIndex property acts as if only one selection was allowed. Setting selectedIndex removes all selections and selects just the single option specified, whereas getting selectedIndex returns only the index of the first option that was selected.

selected property

Options can also be selected by getting a reference to the option and setting its selected property to true. For example, the following selects the first option in a select box: selectbox.options[0].selected = true; Setting the option's selected property does not remove other selections when used in a multi select select box, allowing you to dynamically select any number of options. If an option's selected property is changed in a single-select select box, then all other selections are removed. Setting the selected property to false has no effect in a single-select select box. The selected property is helpful in determining which options in a select box are selected. To get all of the selected options, you can loop over the options collection and test the selected property. Consider this example: function getSelectedOptions(selectbox){ let result = new Array(); for (let option of selectbox.options) { if (option.selected) { result.push(option); } } return result; } This function returns an array of options that are selected in a given select box. First an array to contain the results is created. Then a for loop iterates over the options, checking each option's selected property. If the option is selected, it is added to the result array. The last step is to return the array of selected options. The getSelectedOptions() function can then be used to get information about the selected options, like this: let selectbox = document.getElementById("selLocation"); let selectedOptions = getSelectedOptions(selectbox); let message = ""; for (let option of selectedOptions) { message += 'Selected index: ${option.index}\n' + 'Selected text: ${option.text}\n' + 'Selected value: ${option.value}\n' } console.log(message); In this example, the selected options are retrieved from a select box. A for loop is used to construct a message containing information about all of the selected options, including each option's index, text, and value. This can be used for select boxes that allow single or multiple selection.

DOM Form Select Adding Options

There are several ways to create options dynamically and add them to select boxes using JavaScript.

Use DOM

The first way is to use the DOM as follows: let newOption = document.createElement("option"); newOption.appendChild(document.createTextNode("Option text")); newOption.setAttribute("value", "Option value"); selectbox.appendChild(newOption); This code creates a new <option> element, adds some text using a text node, sets its value attribute, and then adds it to a select box. The new option shows up immediately after being created. New options can also be created using the Option constructor. The Option constructor accepts two arguments, the text and the value, though the second argument is optional. Even though this constructor is used to create an instance of Object, DOM-compliant browsers return an <option> element. This means you can still use appendChild() to add the option to the select box. Consider the following: let newOption = new Option("Option text", "Option value"); selectbox.appendChild(newOption);

add() method

Another way to add a new option is to use the select box's add() method. The DOM specifies that this method accepts two arguments: the new option to add and the option before which the new option should be inserted. To add an option at the end of the list, the second argument should be null. DOM-compliant browsers require the second argument. Instead, passing undefined as the second argument ensures that the option is added at the end of the list in all browsers. Here's an example: let newOption = new Option("Option text", "Option value"); selectbox.add(newOption, undefined); If you need to insert a new option into a position other than last, you should use the DOM technique and insertBefore(). You are not required to assign a value for an option. The Option constructor works with just one argument (the option text).

DOM Form Select Removing Options

There are multiple ways to remove options. You can use the DOM removeChild() method and pass in the option to remove, as shown here: selectbox.removeChild(selectbox.options[0]); // remove first option Or we can use the select box's remove() method. This method accepts a single argument, the index of the option to remove, as shown here: selectbox.remove(0); // remove first option Or we can set the option equal to null. Here's an example: selectbox.options[0] = null; // remove first option To clear a select box of all options, you need to iterate over the options and remove each one, as in this example: function clearSelectbox(selectbox) { for (let option of selectbox.options) { selectbox.remove(0); } } This function removes the first option in a select box repeatedly. Because removing the first option automatically moves all of the options up one spot, this removes all options.

DOM Form Moving and Reordering Options

Using DOM methods, we can move an option from the first select box into the second select box by using the appendChild() method. If you pass an element that is already in the document into this method, the element is removed from its parent and put into the position specified. For example, the following code moves the first option from one select box into another select box. let selectbox1 = document.getElementById("selLocations1"); let selectbox2 = document.getElementById("selLocations2"); selectbox2.appendChild(selectbox1.options[0]); Moving options is the same as removing them in that the index property of each option is reset.

Reorder

To move an option to a particular location in the select box, the insertBefore() method is most appropriate and the appendChild() method can be used to move any option to the last position. To move an option up one spot in the select box, you can use the following code: let optionToMove = selectbox.options[1]; selectbox.insertBefore(optionToMove, selectbox.options[optionToMove.index-1]); In this code, an option is selected to move and then inserted before the option that is in the previous index. The second line of code is generic enough to work with any option in the select box except the first. The following similar code can be used to move an option down one spot: let optionToMove = selectbox.options[1]; selectbox.insertBefore(optionToMove, selectbox.options[optionToMove.index+2]); This code works for all options in a select box, including the last one.

JSON Introduction

JavaScript Object Notation (JSON) is a strict subset of JavaScript. We can use JSON to represent structured data. JSON is a better alternative to XML for accessing structured data in JavaScript because it could be passed directly to eval() and didn't require the creation of a DOM. JSON is a data format, not a programming language. JSON is not a part of JavaScript even though they share syntax. JSON is not only used by JavaScript because it is a data format. There are parser and serializer available in many programming languages.

JSON Syntax

JSON syntax allows the representation of three types of values:
Type Description
Simple values Strings, numbers, Booleans, and null can all be represented in JSON using the same syntax as JavaScript.
The special value undefined is not supported.
Objects objects represent ordered key-value pairs.
Each value may be a primitive type or a complex type.
Arrays arrays represent an ordered list of values that are accessible via a numeric index.
The values may be of any type, including simple values, objects, and even other arrays.
There are no variables, functions, or object instances in JSON. JSON is about representing structured data, and although it shares syntax with JavaScript.

JSON Simple Values

JSON represents a small number of simple values. For example, the following is valid JSON: 5 This is JSON that represents the number 5. Likewise, the following is also valid JSON representing a string: "Hello world!" The big difference between JavaScript strings and JSON strings is that JSON strings must use double quotes to be valid, and single quotes causes a syntax error. Boolean values and null are valid exactly as they are as standalone JSON. In practice, JSON is most often used to represent more complex data structures of which simple values represent just part of the overall information.

JSON Objects

Objects are represented using a slight modification of object literal notation. Object literals in JavaScript look like this: let person = { name: "CSS", age: 29 }; While this is the standard way that developers create object literals, it's the quoted property format that is used in JSON. The following is exactly the same as the previous example: let object = { "name": "CSS", "age": 29 }; The JSON representation of this same object is then: { "name": "CSS", "age": 29 } There is no trailing semicolon. The quotes around the property name are required to be valid JSON. The value can be any simple or complex value, which allows you to embed objects within objects, such as: { "name": "CSS", "age": 29, "school": { "name": "demo2s.com", "location": "online" } } This example embeds school information into the top-level object. Even though there are two properties called "name", they are in two different objects and so are allowed. You do want to avoid having two properties of the same name in the same object. Object property names in JSON must always be double-quoted. It's a common mistake to hand-code JSON without these double quotes or using single quotes.

JSON Arrays

JSON Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript: let values = [25, "hi", true]; You can represent this same array in JSON using a similar syntax: [25, "hi", true] Arrays and objects can be used together to represent more complex collections of data, such as: [ { "title": "JavaScript", "authors": [/* w w w . d e mo 2 s . c om */ "CSS", "HTML" ], "edition": 1, "year": 2020 }, { "title": "Java", "authors": [ "CSS" ], "edition": 3, "year": 2021 }, { "title": "SQL", "authors": [ "demo2s.com" ], "edition": 2, "year": 2029 }, { "title": "Ruby", "authors": [ "abc", "def", "xyz" ], "edition": 2, "year": 2028 }, { "title": "C", "authors": [ "CSS", "HTML", "Javascript" ], "edition": 1, "year": 2027 }, { "title": "C++", "authors": [ "CSS" ], "edition": 1, "year": 2026 } ] This array contains a number of objects representing books. Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure and can be used to create a large number of data structures.

JSON Parsing

JSON data could be parsed into a usable object in JavaScript. XML was parsed into a DOM document, making extraction of data into a bit harder for JavaScript developers. Consider the following JSON String: [ { "title": "JavaScript", "authors": [/* w ww .d e m o 2 s .c o m */ "CSS", "HTML" ], "edition": 1, "year": 2020 }, { "title": "Java", "authors": [ "CSS" ], "edition": 3, "year": 2021 }, { "title": "SQL", "authors": [ "demo2s.com" ], "edition": 2, "year": 2029 }, { "title": "Ruby", "authors": [ "abc", "def", "xyz" ], "edition": 2, "year": 2028 }, { "title": "C", "authors": [ "CSS", "HTML", "Javascript" ], "edition": 1, "year": 2027 }, { "title": "C++", "authors": [ "CSS" ], "edition": 1, "year": 2026 } ] The JSON code in the previous section contains a list of books, and you can easily get the title of the third book via: books[2].title This assumes that the data structure was stored in a variable named books. Compare this to a typical walk through of a DOM structure: doc.getElementsByTagName("book")[2].getAttribute("title");

JSON Parsing Options

The JSON.parse() method accepts an additional argument, which is a function that is called on each key-value pair. The function is called a reviver function to distinguish it from the replacer (filter) function that JSON.stringify() accepts. The format is exactly the same: the function receives two arguments, the key and the value, and needs to return a value. If the reviver function returns undefined, then the key is removed from the result; If it returns any other value, that value is inserted into the result. A very common use of the reviver function is to turn date strings into Date objects. For example: let book = { title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 1, year: 2021, releaseDate: new Date(2021, 11, 1) }; let jsonText = JSON.stringify(book); let bookCopy = JSON.parse(jsonText, (key, value) => key == "releaseDate" ? new Date(value) : value); console.log(bookCopy.releaseDate.getFullYear()); Output: This code starts with the addition of a releaseDate property to the book object, which is a Date. The object is serialized to get a valid JSON string and then parsed back into an object, bookCopy. The reviver function looks for the "releaseDate" key and, when found, creates a new Date object based on that string. The resulting bookCopy.releaseDate property is then a Date object so the getFullYear() method can be called.

JSON Object

JSON object as parser is supported in all major browsers. The JSON object has two methods: stringify() and parse(). In simple usage, these methods serialize JavaScript objects into a JSON string and parse JSON into a native JavaScript value, respectively. For example: let book = { title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 4, year: 2021 }; let jsonText = JSON.stringify(book); console.log(jsonText); Output: This example serializes a JavaScript object into a JSON string using JSON.stringify() and stores it in jsonText. By default, JSON.stringify() outputs a JSON string without any extra white space or indentation. When serializing a JavaScript object, all functions and prototype members are intentionally omitted from the result. Any property whose value is undefined is also skipped. You're left with just a representation of the instance properties that are one of the JSON data types. A JSON string can be passed directly into JSON.parse() and it creates an appropriate JavaScript value. For example, you can create an object similar to the book object using this code: let bookCopy = JSON.parse(jsonText); console.log(bookCopy); Output: Note that book and bookCopy are each separate objects without any relationship to one another even though they do share the same properties. An error is thrown if the text passed into JSON.parse() is not valid JSON.

JSON Serialization Options

The JSON.stringify() method actually accepts two arguments in addition to the object to serialize. These arguments allow you to specify alternate ways to serialize a JavaScript object. The first argument is a filter, which can be either an array or a function, and the second argument is an option for indenting the resulting JSON string. When used separately or together, this provides some very useful functionality for controlling JSON serialization.

Filtering Results

If the argument is an array, then JSON.stringify() will include only object properties that are listed in the array. Consider the following: let book = { title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 4, year: 2027 }; let jsonText = JSON.stringify(book, ["title", "edition"]); console.log(jsonText); Output: The second argument to JSON.stringify() is an array with two strings: "title" and "edition". These correspond to properties in the object being serialized, so only those properties appear in the resulting JSON string. When the second argument is a function, the provided function receives two arguments: the property key name and the property value. You can look at the key to determine what to do with the property. The key is always a string but might be an empty string if a value isn't part of a key-value pair. In order to change the serialization of the object, return the value that should be included for that key. Returning undefined will result in the property being omitted from the result. Here's an example: let book = {/*w w w . de m o 2 s . c o m */ title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 1, year: 2020 }; let jsonText = JSON.stringify(book, (key, value) => { switch(key) { case "authors": return value.join(",") case "year": return 2021; case "edition": return undefined; default: return value; } }); console.log(jsonText); Output: The function filters based on the key. The "authors" key is translated from an array to a string, the "year" key is set to 2021, and the "edition" key is removed altogether by returning undefined. It's important to provide a default behavior that returns the passed-in value so that all other values are passed through to the result. The first call to this function actually has key equal to an empty string and the value set to the book object. The filters apply to all objects contained in the object to be serialized, so an array of multiple objects with these properties will result in every object including only the "title" and "edition" properties.

JSON String Indentation

The third argument of JSON.stringify() controls indentation and white space. When this argument is a number, it represents the number of spaces to indent each level. For example, to indent each level by four spaces, use the following: let book = { title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 1, year: 2020 }; let jsonText = JSON.stringify(book, null, 4); console.log(jsonText); Output: JSON.stringify() also inserts new lines into the JSON string for easier reading. This happens for all valid indentation argument values. The maximum numeric indentation value is 10; passing in a value larger than 10 automatically sets the value to 10. If the indentation argument is a string instead of a number, then the string is used as the indentation character for the JSON string instead of a space. Using a string, you can set the indentation character to be a tab or something completely arbitrary like two dashes: let jsonText = JSON.stringify(book, null, "--"); The jsonText value then becomes: { --"title": "JavaScript", --"authors": [ ----"CSS", ----"HTML" --], --"edition": 1, --"year": 2020 } There is a ten-character limit on the indentation string to use. If a string longer than ten characters is used, then it is truncated to the first ten characters.

JSON toJSON() Method

If objects need custom JSON serialization above and beyond what JSON.stringify() can do, you can add a toJSON() method to the object and have it return the proper JSON representation for itself. The native Date object has a toJSON() method that automatically converts JavaScript Date objects into an ISO 8601 date string. A toJSON() method can be added to any object, for example: let book = { title: "JavaScript", authors: [ "CSS", "HTML" ], edition: 1, year: 2021, toJSON: function() { return this.title; } }; let jsonText = JSON.stringify(book); Output: This code defines a toJSON() method on the book object that simply returns the title of the book. This object is serialized to a simple string instead of an object. You can return any serialization value from toJSON(), and it will work appropriately. Returning undefined causes the value to become null if the object is embedded in another object or else is just undefined if the object is top-level. An arrow function is not used for the toJSON() method because the lexical scope of the arrow function will be the global scope, which is unhelpful in this example. The toJSON() method can be used in addition to the filter function. When an object is passed into JSON.stringify(), the following steps are taken: Call the toJSON() method if it's available to retrieve the actual value. Use the default serialization otherwise. If the second argument is provided, apply the filter. The value that is passed into a filter function will be the value returned from Step 1. Each value from Step 2 is serialized appropriately. If the third argument is provided, format appropriately.

HTML Getting Started with the Canvas Element

The <canvas> element is pretty simple in that all of its functionality is exposed through a JavaScript object, so the element itself only has two attributes.
Item Description
Element: <canvas>
Element Type: Phrasing/Flow
Permitted
Parents:
Any element that can contain phrasing or flow elements
Local Attributes: height, width
Contents: Phrasing or flow content
Tag Style: Start and end tag.
New in HTML5? Yes
Changes in
HTML5
N/A
Style Convention None
The content of a canvas element is used as a fallback if the browser doesn't support the element itself. The following code shows the canvas element and some simple fallback content. Using the canvas element with basic fallback content. <canvas width="500" height="200"> Your browser doesn't support the <code>canvas</code> element </canvas>
Open in separate window
<html> <head> <style> canvas {border: medium double black; margin: 4px} </style> </head> <body> <canvas width="500" height="200"> Your browser doesn't support the <code>canvas</code> element </canvas> </body> </html> The width and height attributes specify the size of the element on screen. We applied a style to the canvas element in this example to set a border. Otherwise there would be no way to see the canvas in the browser window.

HTML Getting a Canvas Context

In order to draw on a canvas element, we need to get a context object, which is an object that exposes drawing functions for a particular style of graphics. In our case, we will be working with the 2d context, which is used to perform two-dimensional operations. Some browsers provide support for an experimental 3D context. We get a context through the object that represents the canvas element in the DOM. This object, HTMLCanvasElement, is described in the following table.
Member Description Returns
height Corresponds to the height attribute number
width Corresponds to the width attribute number
getContext(<context>) Returns a drawing context for the canvas object
The key method is getContext() - to get the two-dimensional context object, we request pass the 2d argument to the method. Once we have the context, we can begin drawing. Obtaining a two-dimensional context object for a canvas. <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(10, 10, 50, 50); </script>
Open in separate window
<html> <head> <style> canvas {border: medium double black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="100"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(10, 10, 50, 50); </script> </body> </html> We use the document object to find the object representing the canvas element in the DOM and call the getContext method, using the argument 2d. Once we have the context object, we can begin to draw. In this example, we have called the fillRect() method, which draws a filled rectangle on the canvas.

HTML Canvas 2d rendering context

The drawing method from canvas are from 2d rendering context. We can get the 2d rendering context via getContext("2d") method: let context = canvasElement.getContext("2d");
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let text = "Hello, World!"; // String of text to display context.font = "italic 30px serif";// Change the size and font context.fillText(text, 40, 40); // Draw the text </script> </body> </html>

HTML Canvas coordinate system

The 2d rendering context is a standard screen-based drawing platform. It uses a flat Cartesian coordinate system with the origin (0, 0) at the top left. Moving to the right will increase the x value, and moving downwards will increase the y value. Understanding how the coordinate system works is integral if you want to have things draw in the right place.
canvas-coordinate-system.png

A single unit in the coordinate system is usually equivalent to 1 pixel on the screen, so the position (24, 30) would be 24 pixels right and 30 pixels down. There are some occasions where a unit in the coordinate system might equal 2 pixels, like with high definition displays, but the general rule of thumb is that 1 coordinate unit equals 1 screen pixel. The following code draw a rectangle: context.fillRect(40, 40, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black; margin: 4px' id="canvas" width="500" height="200"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.fillRect(40, 40, 100, 100); </script> </body> </html>

HTML Canvas Drawing Rectangles

The following table describes the relevant methods, all of which we apply to the context object and not the canvas itself.
Name Description Returns
clearRect(x, y, w, h) Clears the specified rectangle void
fillRect(x, y, w, h) Draws a filled rectangle void
strokeRect(x, y, w, h) Draws an unfilled rectangle void
All three of these methods take four arguments. The first two (x and y as shown in the table) are the offset from the top-left corner of the canvas element. The w and h arguments specify the width and height of the rectangle to draw. The following code shows the use of the fillRect() and strokeRect() methods. let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10; let size = 50; let count = 5; for (let i = 0; i < count; i++) { ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10;<!-- w w w . d em o 2 s . co m --> let size = 50; let count = 5; for (let i = 0; i < count; i++) { ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); } </script> </body> </html> The script in this example uses the fillRect() and strokeRect() methods to create a series of filled and unfilled rectangles. We used a JavaScript for loop to draw these rectangles. The clearRect() method removes whatever has been drawn in the specified rectangle. The following code provides a demonstration using the clearRect() method. let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10; let size = 50; let count = 5; for (let i = 0; i < count; i++) { ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); ctx.clearRect(i * (offset + size) + offset, offset + 5, size, size -10); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10;<!-- w w w . d e m o 2 s . co m--> let size = 50; let count = 5; for (let i = 0; i < count; i++) { ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); ctx.clearRect(i * (offset + size) + offset, offset + 5, size, size -10); } </script> </body> </html> In this example, we use the clearRect() method to clear an area of the canvas that has previously been drawn on by the fillRect method.

HTML Setting the Canvas Drawing State

Drawing operations are configured by the drawing state. This is a set of properties that specify everything from line width to fill color. When we draw a shape, the current settings in the drawing state are used. The following code provides a demonstration, using the lineWidth property, which is part of the drawing state and sets the width of lines used for shapes such as those produced by the strokeRect() method. let ctx = document.getElementById("canvas").getContext("2d"); ctx.lineWidth = 2; ctx.strokeRect(10, 10, 50, 50); ctx.lineWidth = 4; ctx.strokeRect(70, 10, 50, 50); ctx.lineWidth = 6; ctx.strokeRect(130, 10, 50, 50); ctx.strokeRect(190, 10, 50, 50);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="70"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.lineWidth = 2;<!-- w w w . d e m o 2 s . c om --> ctx.strokeRect(10, 10, 50, 50); ctx.lineWidth = 4; ctx.strokeRect(70, 10, 50, 50); ctx.lineWidth = 6; ctx.strokeRect(130, 10, 50, 50); ctx.strokeRect(190, 10, 50, 50); </script> </body> </html> When we use the strokeRect() method, the current value of the lineWidth property is used to draw the rectangle. In the example, we set the property value to 2, 4, and finally 6 pixels, which has the effect of making the lines of the rectangles thicker. Note that we have not changed the value between the last two calls to strokeRect(). The following table shows the basic drawing state properties.
Name Description Default
fillStyle Gets or sets the style used for filled shapes black
lineJoin Gets or sets the style used when lines meet in a shape miter
lineWidth Gets or sets the width of lines 1.0
strokeStyle Gets or sets the style used for lines black

Setting the Line Join Style

The lineJoin property determines how lines that join one another are drawn. There are three values: round, bevel, and miter. The default value is miter. Setting the lineJoin property. let ctx = document.getElementById("canvas").getContext("2d"); ctx.lineWidth = 20;// w w w . d e m o 2 s . c o m ctx.lineJoin = "round"; ctx.strokeRect(20, 20, 100, 100); ctx.lineJoin = "bevel"; ctx.strokeRect(160, 20, 100, 100); ctx.lineJoin = "miter"; ctx.strokeRect(300, 20, 100, 100); <!DOCTYPE HTML> <html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.lineWidth = 20; ctx.lineJoin = "round"; ctx.strokeRect(20, 20, 100, 100); ctx.lineJoin = "bevel"; ctx.strokeRect(160, 20, 100, 100); ctx.lineJoin = "miter"; ctx.strokeRect(300, 20, 100, 100); </script> </body> </html> In this example, we have used the lineWidth property so that the strokeRect() method will draw rectangles with very thick lines and then used each of the lineJoin style values in turn.

Setting the Fill & Stroke Styles

When we set a style using the fillStyle or strokeStyle properties, we can specify a color using the CSS color values using either a name or a color model. Setting colors using the fillStyle and strokeStyle properties. let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10;// w w w. d e m o 2 s .c o m let size = 50; let count = 5; ctx.lineWidth = 3; let fillColors = ["black", "grey", "lightgrey", "red", "blue"]; let strokeColors = ["rgb(0,0,0)", "rgb(100, 100, 100)", "rgb(200, 200, 200)", "rgb(255, 0, 0)", "rgb(0, 0, 255)"]; for (let i = 0; i < count; i++) { ctx.fillStyle = fillColors[i]; ctx.strokeStyle = strokeColors[i]; ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let offset = 10;<!-- w w w . d e mo 2s . c om --> let size = 50; let count = 5; ctx.lineWidth = 3; let fillColors = ["black", "grey", "lightgrey", "red", "blue"]; let strokeColors = ["rgb(0,0,0)", "rgb(100, 100, 100)", "rgb(200, 200, 200)", "rgb(255, 0, 0)", "rgb(0, 0, 255)"]; for (let i = 0; i < count; i++) { ctx.fillStyle = fillColors[i]; ctx.strokeStyle = strokeColors[i]; ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); } </script> </body> </html> In this example, we define two arrays of colors using the CSS color names and the rgb model. We then assign these colors to the fillStyle() and strokeStyle() properties in the for loop which calls the fillRect() and strokeRect() methods.

HTML Canvas Using Gradients

We can also set the fill and stroke styles using gradients, rather than solid colors. A gradient is a gradual progression between two or more colors. The canvas element supports two kinds of gradients: linear and radial, using the methods described in the following table.
Name Description Returns
createLinearGradient(x0, y0, x1, y1) Creates a linear gradient CanvasGradient
createRadialGradient(x0, y0, r0, x1, y1, r1) Creates a radial gradient CanvasGradient
Both of these methods return a CanvasGradient object. CanvasGradient object defines the addColorStop(<position>, <color>) to adds a solid color to the gradient line. The arguments describe the line or circle used by the gradient.

Using a Linear Gradient

A linear gradient is one in which we specify the colors we want along a line. The following code shows how we can create a simple linear gradient. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(0, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(0, 0, 500, 140);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(0, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- w w w . d e m o 2 s . c o m--> ctx.fillRect(0, 0, 500, 140); </script> </body> </html> When we use the createLinearGradient() method, we supply four values that are used as the start and end coordinates of a line on the canvas. In this example, we have used coordinates to describe a line that starts at the point 0, 0 and ends at 500, 140. These points correspond to the top-left and bottom-right corners of the canvas. The line represents the gradient. We can now use the addColorStop() method on the CanvasGradient returned by the createLinearGradient() method to add colors along the gradient line, like this: grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); The first argument to the addColorStop() method is the position on the line that we want to apply the color, which we specify using the second argument. The start of the line (the coordinate 0, 0 in this example) is represented by the value 0 and the end of the line by the value 1. In the example, we have told the canvas that we want the color red at the start of the line, the color white half way along the line, and the color black at the end of the line. The canvas will then work out how to gradually transition between those colors at those points. We can specify as many color stops as we like. Once we have defined the gradient and added the color stops, we can assign the CanvasGradient object to set the fillStyle or strokeStyle properties, like this: ctx.fillStyle = grad; Finally, we can draw a shape. In this example, we drew a filled rectangle, like this: ctx.fillRect(0, 0, 500, 140); This rectangle fills the canvas, showing the entire gradient. You can see that the colors change along the line of the gradient. There is solid red in the top-left corner, solid white in the middle of the line, and solid black in the bottom-right corner, and the color gradually shifts between these points.

Using a Linear Gradient with a Smaller Shape

When we define the gradient line, we do so relative to the canvas - not the shapes that we draw. The following code contains a demonstration of what we mean. Using a gradient with a shape that doesn't fill the canvas. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(0, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(10, 10, 50, 50);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(0, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- ww w . d e m o2 s . c o m --> ctx.fillRect(10, 10, 50, 50); </script> </body> </html> The change in this example is simply to make the rectangle smaller. This is what we mean about the gradient line relating to the canvas. We have drawn my rectangle in a region that is solid red. When we draw a shape, we are allowing part of the underlying gradient show through, which means we have to think about how the gradient line relates to the area we are going to expose. The following code shows how we can target the gradient line for a shape. Making the gradient line match a desired shape. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(0, 0, 500, 140);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- w w w . d e m o 2 s . c o m--> ctx.fillRect(0, 0, 500, 140); </script> </body> </html> In this example, we have set the gradient line so that it starts and stops within the area that we want to reveal with my smaller rectangle. However, we have drawn the rectangle to reveal all of the gradient so you can see the effect of the change. You can see how the gradations have been shifted to the area we are going to expose with the smaller rectangle. The last step is to match the rectangle to the gradient. The following code is Matching the shape to the gradient. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(10, 10, 50, 50);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- w w w. de m o 2s . c om --> ctx.fillRect(10, 10, 50, 50); </script> </body> </html> Notice that the numeric values we used as arguments in the createLinearGradient() method are different from the parameters we used in the fillRect method. The createLinearGradient() values represent a pair of coordinates in the canvas, whereas the fillRect() values represent the width and height of a rectangle relative to a single coordinate. If you find that the gradient and shape don't line up, this is likely to be the cause of the problem. We might want to expose a specific region of a larger gradient in order to get a different effect. Whatever the goal, it is important to understand the relationship between the gradient and the shapes that we use it with.

Radial

There are two types of gradient available to you in canvas: linear and radial. Each type of gradient is created using its own method in the 2d rendering context. For a linear gradient, you use createLinearGradient(), and for a radial gradient you use createRadialGradient(). Both of these methods return a CanvasGradient object for you to further manipulate using the addColorStop method of the CanvasGradient object itself. let gradient = context.createLinearGradient(0, 0, 0, canvas.height); gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(255, 255, 255)"); context.fillStyle = gradient; context.fillRect(0, 0, canvas.width, canvas.height);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let gradient = context.createLinearGradient(0, 0, 0, canvas.height()); gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(255, 255, 255)"); context.fillStyle = gradient; context.fillRect(0, 0, canvas.width(), canvas.height()); </script> </body> </html> The first thing you're doing here is creating a new CanvasGradient object using createLinearGradient(). There are four arguments in the createLinearGradient method; the (x , y) coordinates for the start point of the gradient, and the (x ,) coordinates for the end point of the gradient. The start and end points describe the length, position, and direction that the gradient is drawn. In the example you're drawing a gradient from the canvas origin in the top left, all the way to the bottom left. A linear gradient is drawn perpendicular to the line described by the start and end points, so in the example the gradient will be going from top to bottom. Then we add colors to the gradient via the addColorStop() method of the CanvasGradient object. There are two arguments in the addColorStop method: the offset of the color (between 0 for the start, and 1 for the end of the gradient), and a color value for that offset. The color value can be any CSS color value, just like fillStyle. In the example the gradient is going from black at the start (an offset of 0) to white at the end (an offset of 1). Finally, the gradient is applied as a color value to the fillStyle property, which gives you a gradient from black to white that covers the entire canvas.

Radial gradient

A radial gradient is created using the createRadialGradient() method. This method requires six arguments: the first three describe one circle (the start circle), and the last three describe another (the last circle). These two circles themselves describe not only the direction and where the gradient starts and ends, but also the shape of the gradient. The three arguments that describe each circle are the (x , y) coordinate of the circle origin and the radius. The arguments described as strings are: createRadialGradient(x0, y0, r0, x1, y1, r1); Written in canvas code, this would look a little something like this: let gradient = context.createRadialGradient(300, 300, 10, 100, 100, 50); gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(150, 150, 150)"); context.fillStyle = gradient; context.fillRect(0, 0, canvas.width(), canvas.height());
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let gradient = context.createRadialGradient(300, 180, 10, 100, 100, 50); gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(150, 150, 150)"); context.fillStyle = gradient; context.fillRect(0, 0, 500, 180); </script> </body> </html>

Example

Put the start and end circles at the same origin. let canvasCentreX = canvas.width()/2; let canvasCentreY = canvas.height()/2; let gradient = context.createRadialGradient(canvasCentreX, canvasCentreY, 0, canvasCentreX, canvasCentreY, 250); gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(150, 150, 150)"); context.fillStyle = gradient; context.fillRect(0, 0, canvas.width(), canvas.height());
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let canvasCentreX = canvas.width/2; let canvasCentreY = canvas.height/2; let gradient = context.createRadialGradient(canvasCentreX, canvasCentreY, 0, canvasCentreX, canvasCentreY, 250);<!-- w w w . d e mo 2 s. c o m--> gradient.addColorStop(0, "rgb(0, 0, 0)"); gradient.addColorStop(1, "rgb(150, 150, 150)"); context.fillStyle = gradient; context.fillRect(0, 0, canvas.width, canvas.height); </script> </body> </html>

HTML Canvas Using a Radial Gradient

We define radial gradients using two circles. The start of the gradient is defined by the first circle, the end of the gradient by the second circle and we add color stops between them. The following code provides an example using a radial gradient. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createRadialGradient(250, 70, 20, 200, 60, 100); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(0, 0, 500, 140);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createRadialGradient(250, 70, 20, 200, 60, 100); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- w w w . d em o 2 s. c o m --> ctx.fillRect(0, 0, 500, 140); </script> </body> </html> The six arguments to the createRadialGradient method represent: The coordinate for the center of the start circle (the first and second arguments) The radius of the start circle (the third argument) The coordinate for the center of the finish circle (the fourth and fifth arguments) The radius of the finish circle (the sixth argument) Notice that we can specify gradients that are outside of the canvas. In this example, the start circle is the smaller one and is encompassed by the finish circle. When we add color stops on this gradient, they are placed on a line between the edge of the start circle (a stop value of 0.0) and the edge of the finish circle (a stop value of 1.0). The following code creates a pair of smaller shapes that reveal subsections of the gradient. Using smaller shapes with a radial gradient. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createRadialGradient(250, 70, 20, 200, 60, 100); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad; ctx.fillRect(150, 20, 75, 50); ctx.lineWidth = 8; ctx.strokeStyle = grad; ctx.strokeRect(250, 20, 75, 50);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createRadialGradient(250, 70, 20, 200, 60, 100); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); ctx.fillStyle = grad;<!-- w w w . d e m o 2 s . c o m --> ctx.fillRect(150, 20, 75, 50); ctx.lineWidth = 8; ctx.strokeStyle = grad; ctx.strokeRect(250, 20, 75, 50); </script> </body> </html> Notice that we are able to use the gradient for both the fillStyle() and strokeStyle() properties, enabling us to use gradients for lines as well as solid shapes.

HTML Canvas Using Patterns

We can create patterns using the createPattern() method, which is defined by the canvas context object. The 2D drawing context defines support for three types of pattern - image, video, and canvas. To use an image pattern, we pass an HTMLImageElement object as the first argument to the createPattern method. The second argument is the repeat style, which must be one of the values shown in the following table.
Value Description
repeat The image should be repeated vertically and horizontally
repeat-x The image should be repeated horizontally
repeat-y The image should be repeated vertically
no-repeat The image should not be repeated in the pattern
The following code shows how we can create and use an image pattern. let ctx = document.getElementById("canvas").getContext("2d"); let imageElem = document.getElementById("myImage"); let pattern = ctx.createPattern(imageElem, "repeat"); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 500, 140);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <img id="myImage" hidden src="css.png"/> <script> let ctx = document.getElementById("canvas").getContext("2d"); let imageElem = document.getElementById("myImage"); let pattern = ctx.createPattern(imageElem, "repeat"); ctx.fillStyle = pattern;<!-- w w w. d e m o 2 s . c o m--> ctx.fillRect(0, 0, 500, 140); </script> </body> </html> The document in this example contains an <img> element, which isn't visible to the user because we have applied the hidden attribute. In the script, we use the DOM to locate the HTMLImageElement object that represents the img element as the first argument to the createPattern() method. For the second argument, we use the repeat value, which causes the image to be repeated in both directions. Finally, we set the pattern as the value for the fillStyle() property and use the fillRect() method to draw a filled rectangle which is the same size as the canvas. The pattern is copied from the current state of the <img> element, meaning the pattern won't change if we use JavaScript and the DOM to change the value of the src attribute value of the <img> element. The pattern applies to the entire canvas and we decide which portions of the pattern are shown by the shapes we draw. The following code shows using the pattern for smaller fill and stroke shapes. Using smaller shapes with an image pattern. let ctx = document.getElementById("canvas").getContext("2d"); let imageElem = document.getElementById("myImage"); let pattern = ctx.createPattern(imageElem, "repeat"); ctx.fillStyle = pattern; ctx.fillRect(150, 20, 75, 50); ctx.lineWidth = 8; ctx.strokeStyle = pattern; ctx.strokeRect(250, 20, 75, 50);
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <img id="myImage" hidden src="css.png"/> <script> let ctx = document.getElementById("canvas").getContext("2d"); let imageElem = document.getElementById("myImage"); let pattern = ctx.createPattern(imageElem, "repeat"); ctx.fillStyle = pattern;<!-- w w w . d e m o 2 s . c o m --> ctx.fillRect(150, 20, 75, 50); ctx.lineWidth = 8; ctx.strokeStyle = pattern; ctx.strokeRect(250, 20, 75, 50); </script> </body> </html>

HTML Canvas Saving and Restoring Drawing State

Drawing State

In canvas, the drawing state refers to a whole range of properties that describe the look and feel of the 2d rendering context. The full list of properties that are referred to as the canvas drawing state are: transformation matrix, clipping region, globalAlpha, globalCompositeOperation, strokeStyle, fillStyle, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, font, textAlign, and textBaseline. We can save the drawing state and return to it later using the methods described in the following table.
Value Description
save() Saves the values for the drawing state properties and pushes them on the state stack
restore() Pops the first set of values from the state stack and uses them to set the drawing state
The saved drawing states are stored in a last-in, first-out (LIFO) stack, such that the last state we saved using the save method is the first one restored by the restore method.

Saving and restoring multiple drawing states

context.fillStyle = "rgb(255, 0, 0)"; context.save(); context.fillRect(50, 50, 100, 100); // Red square context.fillStyle = "rgb(0, 0, 255)"; context.save(); context.fillRect(200, 50, 100, 100); // Blue square context.restore(); context.fillRect(350, 50, 100, 100); // Blue square
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.fillStyle = "rgb(255, 0, 0)"; context.save();<!-- w w w . d em o 2 s . c o m --> context.fillRect(50, 50, 100, 100); // Red square context.fillStyle = "rgb(0, 0, 255)"; context.save(); context.fillRect(200, 50, 100, 100); // Blue square context.restore(); context.fillRect(350, 50, 100, 100); // Blue square </script> </body> </html> The third square is now blue instead of red. This is because the last drawing state that was saved to the stack was the blue fillStyle, so it's the first to be restored. The other state with the red fillStyle is still waiting in the stack; you just need to call restore again to access it: context.restore(); context.fillRect(50, 200, 100, 100); // Red square This will return and remove the final state from the stack, leaving it empty.

Example

The following code shows how to do saving and restoring state. let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(500, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); let colors = ["black", grad, "red", "green", "yellow", "black", "grey"]; let cIndex = 0;/* w w w . d e m o 2 s . c o m*/ ctx.fillStyle = colors[cIndex]; draw(); let buttons = document.getElementsByTagName("button"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = handleButtonPress; } function handleButtonPress(e) { switch (e.target.innerHTML) { case 'Save': ctx.save(); cIndex = (cIndex + 1) % colors.length; ctx.fillStyle = colors[cIndex]; draw(); break; case 'Restore': cIndex = Math.max(0, cIndex -1); ctx.restore(); draw(); break; } } function draw() { ctx.fillRect(0, 0, 500, 140); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140" preload="auto"> Your browser doesn't support the <code>canvas</code> element </canvas> <div> <button>Save</button> <button>Restore</button> </div> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(500, 0, 500, 140); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); let colors = ["black", "white", "red", "green", "yellow", "black", "grey"]; let cIndex = 0;<!-- ww w . de m o 2s . c o m --> ctx.fillStyle = colors[cIndex]; draw(); let buttons = document.getElementsByTagName("button"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = handleButtonPress; } function handleButtonPress(e) { switch (e.target.innerHTML) { case 'Save': ctx.save(); cIndex = (cIndex + 1) % colors.length; ctx.fillStyle = colors[cIndex]; draw(); break; case 'Restore': cIndex = Math.max(0, cIndex -1); ctx.restore(); draw(); break; } } function draw() { ctx.fillRect(0, 0, 500, 140); } </script> </body> </html> In this example, we have defined an array that contains CSS color names and a linear gradient. The current drawing state is saved using the save method when the Save button is pressed. When the Restore button is pressed, the previous drawing state is restored. After either button press, the draw function is called, which uses the fillRect() method to draw a filled rectangle. The fillStyle() property is advanced and retarded in the array and saved and restored when the buttons are pressed because this property is part of the drawing state. The contents of the canvas are not saved or restored; only the property values for the drawing state are saved or restored.

HTML Canvas Using Paths

The canvas element and its context provide a set of methods that allow us to draw shapes using paths. Paths are essentially a set of individual lines, known as sub-paths, which cumulatively form a shape. The following table shows the methods that are available for drawing basic paths.
Name Description Returns
beginPath() Begins a new path void
closePath() Attempts to close the existing path by drawing a line from the
end of the last line to the initial coordinates
void
fill() Fills the shape described by the sub-paths void
isPointInPath(x, y) Returns true if the specified point is contained by the shape
described by the current path
boolean
lineTo(x, y) Draws a sub-path to the specified coordinates void
moveTo(x, y) Moves to the specified coordinates without drawing a sub-path void
rect(x, y, w, h) Draws a rectangle whose top-left corners is at (x, y) with width w
and height h.
void
stroke() Draws the outline of the shape as described by the sub-paths void
The basic sequence for drawing a path is as follows: Call the beginPath() method Move to the start position using the moveTo method Draw sub-paths with methods such as arc, lineTo, etc. Optionally call the closePath method Call the fill or stoke methods We can draw more than one line at a time and have them combine to make a single shape. context.beginPath(); context.moveTo(100, 50); context.lineTo(150, 150); context.lineTo(50, 150); context.closePath(); context.stroke(); context.fill();
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); context.beginPath();<!-- w w w . d e mo 2 s . c o m --> context.moveTo(100, 50); context.lineTo(150, 150); context.lineTo(50, 150); context.closePath(); context.stroke(); context.fill(); </script> </body> </html> The code begins a path, moves the origin of the current path, draws a line from the current path origin to a particular point, and it draws another line to another point. Any call to moveTo() or lineTo() will add the corresponding (x , y) coordinate value to something called a sub path. In fact, moveTo() actually creates a whole new sub path, where as lineTo() just adds on to an existing sub path. This sub path keeps track of the last coordinate value that was added to it, which is exactly how you can call multiple lineTo methods in a row. Each lineTo() you call starts from the last coordinate value in the sub path left by a moveTo call or a lineTo call, draws a line all the way to the coordinate value defined in the lineTo arguments, and then updates the sub path with that new coordinate value.

HTML Canvas Drawing Paths with Lines

The simplest paths are those made up of straight lines. The following code provides a demonstration creating a path from straight-lines. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4;/* ww w . d e m o 2 s . c o m */ ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(110, 10); ctx.lineTo(110, 120); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(150, 10); ctx.lineTo(200, 10); ctx.lineTo(200, 120); ctx.lineTo(190, 120); ctx.fill(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(250, 10); ctx.lineTo(250, 120); ctx.stroke();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4;<!-- w w w . d e m o 2s . c om --> ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(110, 10); ctx.lineTo(110, 120); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(150, 10); ctx.lineTo(200, 10); ctx.lineTo(200, 120); ctx.lineTo(190, 120); ctx.fill(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(250, 10); ctx.lineTo(250, 120); ctx.stroke(); </script> </body> </html> In this example, we have created three paths. For the first path, we explicitly drew two lines and then used the closePath() method. The canvas will close the path. We then call the fill method to fill the shape with the style specified by the fillStyle property. For the second shape, we specified three sub-paths, but didn't close the shape. We called both the fill and stroke methods to fill the shape with color and draw a line along the path. Notice that the fill color is drawn as though the shape were closed. The canvas element assumes a sub-path from the last point to the first and uses this to fill the shape. By contrast, the stroke method only follows sub-paths that have been defined. For the second shape, we called the fill method before the stroke method, which causes the canvas to fill the shape with solid color and then draw a line that follows the path. For the third shape, we have simply drawn a line between two points because paths don't have to have multiple sub-paths. When we draw lines or leave shapes open, we can use the lineCap property to set the style for how the line is terminated. The three allowed values for this property are: butt, round, and square (butt is the default). The following code shows this property and each of its values in use. Setting the lineCap property. let ctx = document.getElementById("canvas").getContext("2d"); ctx.strokeStyle = "red"; ctx.lineWidth = "2"; ctx.beginPath();/* ww w . d e m o 2 s . c o m*/ ctx.moveTo(0, 50); ctx.lineTo(200, 50); ctx.stroke(); ctx.strokeStyle = "black"; ctx.lineWidth = 40; let xpos = 50; let styles = ["butt", "round", "square"]; for (let i = 0; i < styles.length; i++) { ctx.beginPath(); ctx.lineCap = styles[i]; ctx.moveTo(xpos, 50); ctx.lineTo(xpos, 150); ctx.stroke(); xpos += 50; }
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="200" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.strokeStyle = "red"; ctx.lineWidth = "2"; ctx.beginPath();<!-- w w w . d e m o 2 s .c o m--> ctx.moveTo(0, 50); ctx.lineTo(200, 50); ctx.stroke(); ctx.strokeStyle = "black"; ctx.lineWidth = 40; let xpos = 50; let styles = ["butt", "round", "square"]; for (let i = 0; i < styles.length; i++) { ctx.beginPath(); ctx.lineCap = styles[i]; ctx.moveTo(xpos, 50); ctx.lineTo(xpos, 150); ctx.stroke(); xpos += 50; } </script> </body> </html>

HTML Canvas Drawing Lines

Canvas lines are actually known as paths. To create a simple path, you have to first call the beginPath() method on the 2d rendering context. The next method to call is moveTo, which sets the (x , y) origin of the path we're about to draw. A call to lineTo() with the (x , y) of the destination of our line and with a call to closePath to finish drawing the path. Finally, a call to stroke will make the line visible by drawing its outline. By putting this all together you come with something like this: context.beginPath(); // Start the path context.moveTo(40, 40); // Set the path origin context.lineTo(340, 40); // Set the path destination context.closePath(); // Close the path context.stroke(); // Outline the path
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.beginPath(); // Start the path context.moveTo(40, 40); // Set the path origin context.lineTo(340, 40); // Set the path destination context.closePath(); // Close the path context.stroke(); // Outline the path </script> </body> </html> Lines don't have to be horizontal or vertical though, by changing the (x , y) arguments of the lineTo method you can make it diagonal: context.lineTo(340, 340);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.beginPath(); // Start the path context.moveTo(40, 40); // Set the path origin context.lineTo(340, 340); context.closePath(); // Close the path context.stroke(); // Outline the path </script> </body> </html>

HTML Canvas Changing line width

We can use lineWidth property to change line width. By default the lineWidth property is set to 1, but you can set it to anything you want. For example, let's change the width of our red and black lines: context.lineWidth = 5; // Make lines thick context.strokeStyle = "rgb(255, 0, 0)"; context.beginPath(); context.moveTo(40, 180); context.lineTo(420, 180); // Red line context.closePath(); context.stroke(); context.lineWidth = 20; // Make lines even thicker context.strokeStyle = "rgb(0, 0, 0)"; context.beginPath(); context.moveTo(40, 220); context.lineTo(420, 220); // Black line context.closePath(); context.stroke();
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.lineWidth = 5; // Make lines thick context.strokeStyle = "rgb(255, 0, 0)"; context.beginPath();<!-- w w w .d e m o 2 s . c o m --> context.moveTo(40, 180); context.lineTo(420, 180); // Red line context.closePath(); context.stroke(); context.lineWidth = 20; // Make lines even thicker context.strokeStyle = "rgb(0, 0, 0)"; context.beginPath(); context.moveTo(40, 220); context.lineTo(420, 220); // Black line context.closePath(); context.stroke(); </script> </body> </html> And lineWidth works just as well on shapes: context.lineWidth = 5; // Make lines thick context.strokeStyle = "rgb(255, 0, 0)"; context.strokeRect(40, 40, 100, 100); // Red square context.strokeRect(180, 40, 100, 100); // Red square context.lineWidth = 20; // Make lines even thicker context.strokeStyle = "rgb(0, 0, 0)"; context.strokeRect(320, 40, 100, 100); // Black square
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.lineWidth = 5; // Make lines thick context.strokeStyle = "rgb(255, 0, 0)"; context.strokeRect(40, 40, 100, 100); // Red square context.strokeRect(180, 40, 100, 100); // Red square context.lineWidth = 20; // Make lines even thicker context.strokeStyle = "rgb(0, 0, 0)"; context.strokeRect(320, 40, 100, 100); // Black square </script> </body><!-- ww w . d e m o 2 s . c om --> </html>

HTML Canvas Drawing Rectangles in path

The rect() method adds a rectangular sub-path to the current path. The rect() method is useful when you need to add a rectangle to a more complex shape. The following code is drawing a rectangle with the rect method let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(110, 10); ctx.lineTo(110, 100); ctx.lineTo(10, 10); ctx.closePath(); ctx.rect(110, 10, 100, 90); ctx.rect(110, 100, 130, 30); ctx.fill(); ctx.stroke();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4;<!-- w w w . d e m o 2 s. c o m--> ctx.beginPath(); ctx.moveTo(110, 10); ctx.lineTo(110, 100); ctx.lineTo(10, 10); ctx.closePath(); ctx.rect(110, 10, 100, 90); ctx.rect(110, 100, 130, 30); ctx.fill(); ctx.stroke(); </script> </body> </html> We don't have to use the moveTo() method when using the rect() method because we specify the coordinates of the rectangle as the first two method arguments. In the listing, we have drawn a pair of lines, called closePath to create a triangle and then drawn two adjoining rectangles. Sub-paths don't have to touch to form part of a path. We can have several disconnected sub-paths and they are still treated as being part of the same shape. Working with disconnected sub-paths. ...// w w w .d e m o 2 s .c o m <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(110, 10); ctx.lineTo(110, 100); ctx.lineTo(10, 10); ctx.closePath(); ctx.rect(120, 10, 100, 90); ctx.rect(150, 110, 130, 20); ctx.fill(); ctx.stroke(); </script> ...
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4;<!-- w w w. d e m o 2 s. co m --> ctx.beginPath(); ctx.moveTo(110, 10); ctx.lineTo(110, 100); ctx.lineTo(10, 10); ctx.closePath(); ctx.rect(120, 10, 100, 90); ctx.rect(150, 110, 130, 20); ctx.fill(); ctx.stroke(); </script> </body> </html> In this example, the sub-paths are not connected, but the overall result is still a single path. When we call the stroke or fill methods, the effects are applied to all of the sub-paths we created.

HTML Canvas Drawing Arcs

We use the arc() and arcTo() methods to draw arcs on the canvas, although each method draws the arc in a different way. The following table describes the arc-related methods in the canvas.
Name Description
arc(x, y, rad, start_Angle,
end_Angle,direction)
Draws an arc to (x, y) with radius rad, start angle
start_Angle, and finish angle end_Angle. The optional
direction parameter specifies the direction of the arc
arcTo(x1, y1, x2, y2,rad) Draw an arc to (x2, y2) that passes (x1, y1) and has radius radian

Using the arcTo Method

The following code demonstrates using the arcTo() method. let ctx = document.getElementById("canvas").getContext("2d"); let point1 = [100, 10]; let point2 = [200, 10]; let point3 = [200, 110]; ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.arcTo(point2[0], point2[1], point3[0], point3[1], 100); ctx.stroke();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let point1 = [100, 10];<!-- w w w . d e mo 2 s . c o m--> let point2 = [200, 10]; let point3 = [200, 110]; ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.arcTo(point2[0], point2[1], point3[0], point3[1], 100); ctx.stroke(); drawPoint(point1[0], point1[1]); drawPoint(point2[0], point2[1]); drawPoint(point3[0], point3[1]); ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.lineTo(point2[0], point2[1]); ctx.lineTo(point3[0], point3[1]); ctx.stroke(); function drawPoint(x, y) { ctx.lineWidth = 1; ctx.strokeStyle = "red"; ctx.strokeRect(x -2, y-2, 4, 4); } </script> </body> </html> The arc drawn by the arcTo method depends on two lines. The first line is drawn from the end of the last sub-path to the point described by the first two method arguments. The second line is drawn from the point described by the first two arguments to the point described by the third and fourth arguments. The arc is then drawn as the shortest line between the end of the last sub-path and the second point that describes an arc of a circle with the radius specified by the last argument. To make this easier to understand, we have added some additional paths to the canvas to provide some context. You can see the two lines drawn in red. We have specified a radius and the length of both lines are all the same, which means that we end up with a neat curve that just touches the last point of the previous sub-path and the point described by the third and fourth method arguments. The radius and the line lengths are not always so conveniently sized, so the canvas will adjust the arc it draws as required. The following code uses the events to monitor mouse movements and draw arc lines for different points as the mouse is moved across the screen. Drawing arcs in response to mouse movements. let canvasElem = document.getElementById("canvas"); let ctx = canvasElem.getContext("2d"); let point1 = [100, 10]; let point2 = [200, 10]; let point3 = [200, 110]; draw();/* w w w. d e m o 2 s . co m */ canvasElem.onmousemove = function (e) { if (e.ctrlKey) { point1 = [e.clientX, e.clientY]; } else if(e.shiftKey) { point2 = [e.clientX, e.clientY]; } else { point3 = [e.clientX, e.clientY]; } ctx.clearRect(0, 0, 540, 140); draw(); } function draw() { ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.arcTo(point2[0], point2[1], point3[0], point3[1], 50); ctx.stroke(); drawPoint(point1[0], point1[1]); drawPoint(point2[0], point2[1]); drawPoint(point3[0], point3[1]); ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.lineTo(point2[0], point2[1]); ctx.lineTo(point3[0], point3[1]); ctx.stroke(); } function drawPoint(x, y) { ctx.lineWidth = 1; ctx.strokeStyle = "red"; ctx.strokeRect(x -2, y-2, 4, 4); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let canvasElem = document.getElementById("canvas"); let ctx = canvasElem.getContext("2d"); let point1 = [100, 10];<!-- w w w . d e m o 2 s. c o m--> let point2 = [200, 10]; let point3 = [200, 110]; draw(); canvasElem.onmousemove = function (e) { if (e.ctrlKey) { point1 = [e.clientX, e.clientY]; } else if(e.shiftKey) { point2 = [e.clientX, e.clientY]; } else { point3 = [e.clientX, e.clientY]; } ctx.clearRect(0, 0, 540, 140); draw(); } function draw() { ctx.fillStyle = "yellow"; ctx.strokeStyle = "black"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.arcTo(point2[0], point2[1], point3[0], point3[1], 50); ctx.stroke(); drawPoint(point1[0], point1[1]); drawPoint(point2[0], point2[1]); drawPoint(point3[0], point3[1]); ctx.beginPath(); ctx.moveTo(point1[0], point1[1]); ctx.lineTo(point2[0], point2[1]); ctx.lineTo(point3[0], point3[1]); ctx.stroke(); } function drawPoint(x, y) { ctx.lineWidth = 1; ctx.strokeStyle = "red"; ctx.strokeRect(x -2, y-2, 4, 4); } </script> </body> </html> The script in this example moves different points based on which key is pressed as the mouse is moved. If the control key is pressed, the first point is moved (the one that represents the end of the previous sub-path). If the shift key is pressed, the second point is moved (the point represented by the first two arguments to the arcTo method). If neither key is pressed, the third point is moved (the one represented by the third and fourth method arguments).

Using the arc Method

When using arc() method we specify a point on the canvas using the first two method arguments. We specify the radius of the arc with the third argument and then we specify the start and end angle for the arc. The final argument specifies whether the arc is drawn in the clockwise or anticlockwise direction. The following code gives some examples using the arc method. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.lineWidth = "3"; ctx.beginPath();// w w w .d e m o 2 s . c o m ctx.arc(70, 70, 60, 0, Math.PI * 2, true); ctx.stroke(); ctx.beginPath(); ctx.arc(200, 70, 60, Math.PI/2, Math.PI, true); ctx.fill(); ctx.stroke(); ctx.beginPath(); let val = 0; for (let i = 0; i < 4; i++) { ctx.arc(350, 70, 60, val, val + Math.PI/4, false); val+= Math.PI/2; } ctx.closePath(); ctx.fill(); ctx.stroke();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.lineWidth = "3"; ctx.beginPath();<!-- w ww . d e mo 2 s . co m --> ctx.arc(70, 70, 60, 0, Math.PI * 2, true); ctx.stroke(); ctx.beginPath(); ctx.arc(200, 70, 60, Math.PI/2, Math.PI, true); ctx.fill(); ctx.stroke(); ctx.beginPath(); let val = 0; for (let i = 0; i < 4; i++) { ctx.arc(350, 70, 60, val, val + Math.PI/4, false); val+= Math.PI/2; } ctx.closePath(); ctx.fill(); ctx.stroke(); </script> </body> </html> As the first and second arcs show, we can use the arc() method to draw complete circles or regular arcs. We can use the arc method to create more complex paths. If we use the arc method and we have already drawn a sub-path, then a line is drawn directly from the end of the previous sub-path to the coordinates described by the first two arguments to the arc method.

HTML Canvas Drawing Circles

There isn't actually a special method in canvas to create a circle. What there is is a method for drawing arcs, which is all a circle really is-an arc joined at both ends. context.beginPath(); // Start the path context.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circle context.closePath(); // Close the path context.fill(); // Fill the path
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.beginPath(); // Start the path context.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circle context.closePath(); // Close the path context.fill(); // Fill the path </script> </body> </html> You should already recognize the first and last two lines, they just start and close the path (the arc) and then fill it when we're done. The second line does everything necessary to draw a circle. There are six arguments used in the creation of an arc: the (x , y) coordinate values for the centre of the circle, the radius of the arc, the start angle, the end angle, a boolean value that draws the arc anti-clockwise if true, or clockwise if false. The arc method could be rewritten in a more readable way like so: context.arc(x, y, radius, startAngle, endAngle, anticlockwise); The first three arguments are self-explanatory. An arc in canvas is defined as a curved path that starts at a distance from the (x , y) origin equal to the radius, and is at the angle defined by the start angle. The path ends at the end angle one radius away from the (x , y) origin.
canvas-arc-method.png

Angles in canvas are in radians and not degrees and. 360 degrees (a complete circle) is 2' (pi multiplied by 2) radians. Here is the formula of how to convert from degrees to radians written in JavaScript: let degrees = 1; // 1 degree Let radians = degrees * (Math.PI / 180); // 0.0175 radians When drawing circle, the start angle is 0, the beginning of our arc, and the end angle is Math.PI*2 (pi multiplied by 2);

Semi circle

To draw half a circle. context.arc(230, 90, 50, 0, Math.PI, false); // Draw a semi-circle
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.beginPath(); // Start the path context.arc(230, 90, 50, 0, Math.PI, false); // Draw a semi-circle context.closePath(); // Close the path context.fill(); // Fill the path </script> </body> </html>

HTML Canvas Bezier curves Concept

We can draw bezier curve using either quadraticCurveTo(), or bezierCurveTo() methods. Both methods draw Bezier curves, even if one of them doesn't have Bezier in the name. quadraticCurveTo() draws a quadratic Bezier curve, while bezierCurveTo() is a cubic Bezier curve. Both kinds of Bezier curve use control points to manipulate a straight line into a curve. A quadratic Bezier curve has just one control point, meaning you have only one curve along the line, and a cubic Bezier curve has two controls points, meaning you have two curves along a single line. The following figure should help you visualize how both of these curves actually work. The quadratic Bezier is at the top, with the cubic Bezier at the bottom.
canvas-bezier-curve-control-points.png

Let's start with quadraticCurveTo and see what happens. context.lineWidth = 5; context.beginPath(); context.moveTo(150, 150); context.quadraticCurveTo(50, 10, 300, 50); context.stroke();
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); context.lineWidth = 5; context.beginPath(); context.moveTo(150, 150); context.quadraticCurveTo(50, 10, 300, 50); context.stroke(); </script> </body> </html> quadraticCurveTo() method takes four arguments: the (x , y) coordinate value of the control point (cpx and cpy in figure), and the (x , y) coordinate origin of the destination of the path. The control point has been placed at the horizontal (x) centre of the line and slightly above it in the vertical (y) direction, just like in figure. Creating cubic Bezier curves: context.lineWidth = 5; context.beginPath(); context.moveTo(150, 150); context.bezierCurveTo(150, 50, 50, 150, 50, 150); context.stroke();
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); context.lineWidth = 5; context.beginPath(); context.moveTo(150, 150); context.bezierCurveTo(150, 50, 50, 150, 50, 150); context.stroke(); </script> </body> </html> The bezierCurveTo function takes six arguments the (x , y) coordinate value of the first control point (cp1x and cp1y in figure), the (x , y) coordinate value of the second control point (cp2x and cp2y),and the (x , y) coordinate origin of the destination of the path. Both control points are placed in a similar position to those in figure.

HTML Canvas Drawing Bezier Curves

The canvas supports drawing two kinds of Bezier curves: cubic and quadratic. We pick a start and end point and then add one or more control points that shape the curve. In the examples that follow, we'll add some code to the script to provide some context. The following table shows the methods we can use to draw curves.
Name Description
bezierCurveTo(cx1, cy1, cx2, cy2,
x, y)
Draws a Bezier curve to the point (x, y) with the
control points (cx1, cy1) and (cx2, cy2).
quadraticCurveTo(cx, xy, x, y) Draws a quadratic Bezier curve to (x, y) with the
control point (cx, cy).

Drawing Cubic Bezier Curves

The bezierCurveTo() method draws a curve from the end of the previous sub-path to the point specified by the 5th and 6th method arguments. There are two controls points - these are specified by the first four arguments. The following code shows the use of this method and with some additional paths to make it easier to understand the relationship between the argument values and the curve that is produced. Drawing cubic Bezier curves. let canvasElem = document.getElementById("canvas"); let ctx = canvasElem.getContext("2d"); let startPoint = [50, 100]; let endPoint = [400, 100]; let cp1 = [250, 50]; let cp2 = [350, 50]; canvasElem.onmousemove = function(e) { if (e.shiftKey) { cp1 = [e.clientX, e.clientY];// w ww . d e m o 2s . c o m } else if (e.ctrlKey) { cp2 = [e.clientX, e.clientY]; } ctx.clearRect(0, 0, 500, 140); draw(); } draw(); function draw() { ctx.lineWidth = 3; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(startPoint[0], startPoint[1]); ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], endPoint[0], endPoint[1]); ctx.stroke(); ctx.lineWidth = 1; ctx.strokeStyle = "red"; let points = [startPoint, endPoint, cp1, cp2]; for (let i = 0; i < points.length; i++) { drawPoint(points[i]); } drawLine(startPoint, cp1); drawLine(endPoint, cp2); } function drawPoint(point) { ctx.beginPath(); ctx.strokeRect(point[0] -2, point[1] -2, 4, 4); } function drawLine(from, to) { ctx.beginPath(); ctx.moveTo(from[0], from[1]); ctx.lineTo(to[0], to[1]); ctx.stroke(); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let canvasElem = document.getElementById("canvas"); let ctx = canvasElem.getContext("2d"); let startPoint = [50, 100];<!-- w ww . d em o 2 s . co m --> let endPoint = [400, 100]; let cp1 = [250, 50]; let cp2 = [350, 50]; canvasElem.onmousemove = function(e) { if (e.shiftKey) { cp1 = [e.clientX, e.clientY]; } else if (e.ctrlKey) { cp2 = [e.clientX, e.clientY]; } ctx.clearRect(0, 0, 500, 140); draw(); } draw(); function draw() { ctx.lineWidth = 3; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(startPoint[0], startPoint[1]); ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], endPoint[0], endPoint[1]); ctx.stroke(); ctx.lineWidth = 1; ctx.strokeStyle = "red"; let points = [startPoint, endPoint, cp1, cp2]; for (let i = 0; i < points.length; i++) { drawPoint(points[i]); } drawLine(startPoint, cp1); drawLine(endPoint, cp2); } function drawPoint(point) { ctx.beginPath(); ctx.strokeRect(point[0] -2, point[1] -2, 4, 4); } function drawLine(from, to) { ctx.beginPath(); ctx.moveTo(from[0], from[1]); ctx.lineTo(to[0], to[1]); ctx.stroke(); } </script> </body> </html> To give you a sense of how the curves are drawn, the script in this example moves the control points on a Bezier curve in response to mouse movement. If the shift key is pressed then the first control point is moved. The second control point is moved if the control key is pressed.

Drawing Quadratic Bezier Curves

A quadratic Bezier curve has only one control point and so the quadraticCurveTo() method has two fewer arguments than the bezierCurveTo method. The following code shows the previous example reworked to display a quadratic curve, drawn with the quadraticCurveTo method. Drawing a quadratic Bezier curve. ctx.moveTo(startPoint[0], startPoint[1]); ctx.quadraticCurveTo(cp1[0], cp1[1], endPoint[0], endPoint[1]); ctx.stroke();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let canvasElem = document.getElementById("canvas"); let ctx = canvasElem.getContext("2d"); let startPoint = [50, 100];<!-- w w w .d em o 2 s . c o m --> let endPoint = [400, 100]; let cp1 = [250, 50]; canvasElem.onmousemove = function(e) { if (e.shiftKey) { cp1 = [e.clientX, e.clientY]; } ctx.clearRect(0, 0, 500, 140); draw(); } draw(); function draw() { ctx.lineWidth = 3; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(startPoint[0], startPoint[1]); ctx.quadraticCurveTo(cp1[0], cp1[1], endPoint[0], endPoint[1]); ctx.stroke(); ctx.lineWidth = 1; ctx.strokeStyle = "red"; let points = [startPoint, endPoint, cp1]; for (let i = 0; i < points.length; i++) { drawPoint(points[i]); } drawLine(startPoint, cp1); drawLine(endPoint, cp1); } function drawPoint(point) { ctx.beginPath(); ctx.strokeRect(point[0] -2, point[1] -2, 4, 4); } function drawLine(from, to) { ctx.beginPath(); ctx.moveTo(from[0], from[1]); ctx.lineTo(to[0], to[1]); ctx.stroke(); } </script> </body> </html>

HTML Canvas Drawing Text

We can draw text on the canvas using the following methods.
Name Description
fillText(<text>, x, y, width) Draws and fills the specified text at the position (x, y).
The optional width argument sets an upper limit on
the width of the text
strokeText(<text>, x, y, width) Draws and strokes the specified text at the position
(x, y). The optional width argument sets an upper
limit on the width of the text
There are three drawing state properties that we can use to control the way that text is drawn. The text drawing state properties.
Name Description Returns
font Sets the font used when text is drawn string
textAlign Sets the alignment of the text: start, end, left, right, center string
textBaseline Sets the text baseline: top, hanging, middle, alphabetic, ideographic, bottom string
The following code shows how we can fill and stroke text. We specify the value for the font property using the same format string as for the CSS font shorthand property. Drawing text on the canvas. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3; ctx.font = "100px sans-serif"; ctx.fillText("Hello", 50, 100); ctx.strokeText("Hello", 50, 100);
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="350" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3;<!-- w ww . d e m o 2 s . c o m --> ctx.font = "100px sans-serif"; ctx.fillText("Hello", 50, 100); ctx.strokeText("Hello", 50, 100); </script> </body> </html> Text is drawn using the fillStyle and strokeStyle properties, meaning that we have the same set of colors, gradients and patterns as for shapes. In this example, we have filled and stroked the text in two solid colors. Canvas can display text. let text = "Hello, World!"; context.fillText(text, 40, 40);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let text = "Hello, World!"; context.fillText(text, 40, 40); </script> </body> </html> The fillText() method of the 2d rendering context takes four arguments. The first is the string of text you want to draw, and the second and third are the (x , y) coordinate values for the origin of the text (the bottom left). The default font settings for text in canvas are 10px sans-serif. To change the size, set the font property of the 2d rendering context, like so: let text = "Hello, World!"; context.font = "30px serif"; // Change the size and font context.fillText(text, 40, 40);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let text = "Hello, World!"; context.font = "30px serif"; // Change the size and font context.fillText(text, 40, 40); </script> </body> </html> The font property takes a string value in exactly the same way as the font property in CSS. In the example, you give the pixel size, followed by the name of the font family. You've set it to serif which means the default font on the computer that is a serif font. You could even make the text italic: let text = "Hello, World!"; context.font = "italic 30px serif"; context.fillText(text, 40, 40);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let text = "Hello, World!"; context.font = "italic 30px serif"; context.fillText(text, 40, 40); </script> </body> </html> To create stroked text: let text = "Hello, World!"; context.font = "italic 60px serif"; context.strokeText(text, 40, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let text = "Hello, World!"; context.font = "italic 60px serif"; context.strokeText(text, 40, 100); </script> </body> </html> We used the strokeText() method, which takes exactly the same parameters as fillText().

HTML Canvas Drawing Images

We can draw images on the canvas by using the drawImage() method. This method takes three, five, or nine arguments. The first argument is always the source of the image, which can be the DOM object that represents an img, video, or another canvas element. The following code gives an example, using an <img> element as the source. Using the drawImage method. let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("myImage"); imageElement.onload = function(){ ctx.drawImage(imageElement, 10, 10); ctx.drawImage(imageElement, 120, 10, 100, 120); ctx.drawImage(imageElement, 20, 20, 100, 50, 250, 10, 100, 120); };
Open in separate window
<html> <head> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140" preload="auto"> Your browser doesn't support the <code>canvas</code> element </canvas> <img id="myImage" hidden src="css.png"/> <script> let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("myImage"); imageElement.onload = function(){ ctx.drawImage(imageElement, 10, 10); ctx.drawImage(imageElement, 120, 10, 100, 120); ctx.drawImage(imageElement, 20, 20, 100, 50, 250, 10, 100, 120); <!-- w w w . de m o 2 s. c o m --> }; </script> </body> </html> When using three arguments, the second and third arguments give the coordinate on the canvas at which the image should be drawn. The image is drawn at its intrinsic width and height. When using five arguments, the additional arguments specify the width and height at which the image should be drawn, overriding the intrinsic size. When using nine arguments: The second and third arguments are the offset into the source image. The fourth and fifth arguments are the width and height of the region of the source image that will be used. The sixth and seventh arguments specify the canvas coordinate at which the top-left corner of the selected region will be drawn. The eighth and ninth arguments specify the width and height to which the selected region will be draw.

HTML Canvas Using Canvas Images

We can use the contents of one canvas as the source for the drawImage() method on another. Using a canvas as the source for the drawImage() method. let srcCanvasElement = document.getElementById("canvas"); let ctx = srcCanvasElement.getContext("2d"); let ctx2= document.getElementById("canvas2").getContext("2d"); let imageElement = document.getElementById("vid"); document.getElementById("pressme").onclick = takeSnapshot; let width = 100;/* w w w .d e m o 2 s . co m */ let height = 10; ctx.lineWidth = 5; ctx.strokeStyle = "red"; ctx2.lineWidth = 30; ctx2.strokeStyle = "black;" setInterval(function() { ctx.drawImage(imageElement, 0, 0, 360, 240); ctx.strokeRect(180 - (width/2),120 - (height/2), width, height); }, 25); setInterval(function() { width = (width + 1) % 200; height = (height + 3) % 200; }, 100); function takeSnapshot() { ctx2.drawImage(srcCanvasElement, 0, 0, 360, 240); ctx2.strokeRect(0, 0, 360, 240); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <video id="vid" hidden src="radian.webm" preload="auto" width="360" height="240" autoplay></video> <canvas id="canvas" width="360" height="240"> Your browser doesn't support the <code>canvas</code> element </canvas> <div> <button id="pressme">Press Me</button> </div> <canvas id="canvas2" width="360" height="240"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let srcCanvasElement = document.getElementById("canvas"); let ctx = srcCanvasElement.getContext("2d"); let ctx2= document.getElementById("canvas2").getContext("2d"); let imageElement = document.getElementById("vid"); document.getElementById("pressme").onclick = takeSnapshot; let width = 100; let height = 10; ctx.lineWidth = 5;<!-- w w w . d e m o2 s . c o m--> ctx.strokeStyle = "red"; ctx2.lineWidth = 30; ctx2.strokeStyle = "black;" setInterval(function() { ctx.drawImage(imageElement, 0, 0, 360, 240); ctx.strokeRect(180 - (width/2),120 - (height/2), width, height); }, 25); setInterval(function() { width = (width + 1) % 200; height = (height + 3) % 200; }, 100); function takeSnapshot() { ctx2.drawImage(srcCanvasElement, 0, 0, 360, 240); ctx2.strokeRect(0, 0, 360, 240); } </script> </body> </html> In this example, we have added a second canvas element and a button. When the button is pressed, we use the HTMLCanvasElement object that represents the original canvas as the first argument in a call to the drawImage method on the context object of the second canvas. In essence, pressing the button takes a snapshot of the left-hand canvas and displays it on the right-hand canvas. We copy everything on the canvas, including the red overlaid rectangle.

HTML Canvas Exporting the canvas as an image

Canvas toDataURL() method converts your canvas drawing a data URL, which you can use later to display it as a proper image in the browser. Preparing the canvas to be exported context.fillRect(50, 50, 100, 100); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(100, 100, 100, 100); let dataURL = canvas.get(0).toDataURL(); The dataURL variable has the following value: data:image/png;base64,iVBORw0KGgUTOUIHNt+KAAAXvElEQVR4Ae3XQQ ... CAg The actual output is much, much longer. The starting words data:image/png; describe that the text following is going to be a data URL in the format of a PNG image. The fourth word, base64, describes that the data is in the base64 encoding format. This format is common for the transmission of binary data (like images) over a system that uses text as data. The canvas specification supports other types of images using the toDataURL() method. PNG support is the default requirement and it's up to the individual browser manufacturers to implement support for anything else. You can set the src attribute of an image to the data url. context.fillRect(50, 50, 100, 100); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(100, 100, 100, 100); let dataURL = canvas.toDataURL(); let img = document.getElementById("myImage"); let attr = document.createAttribute("src"); attr.value = dataURL; img.setAttributeNode(attr);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' > <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); context.fillRect(50, 50, 100, 100);<!-- w w w . d e m o2 s. c o m --> context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(100, 100, 100, 100); let dataURL = canvas.toDataURL(); let img = document.getElementById("myImage"); let attr = document.createAttribute("src"); attr.value = dataURL; img.setAttributeNode(attr); </script> </body> </html> base64 data is about 50 percent larger than the original binary image data that it represents.

HTML Canvas Loading an image into canvas

We can load an image into canvas. After that we can perform all of the 2d rendering context methods and transformations on an image that wasn't originally created in canvas. You can also perform a few special pixel manipulation methods on the images. You need to call the drawImage() method with at least three parameters: the image that you're drawing, and the (x , y) coordinate position to draw the image. The method looks like this: context.drawImage(image, x, y); The image argument can be a HTML img element, a HTML5 canvas element, or a HTML5 video element. The following code draws an HTML <img> element to the canvas using an image from the same directory as the HTML file. let imageObj = new Image(); imageObj.onload = function(){ let destX = canvas.width / 2 - this.width / 2; let destY = canvas.height / 2 - this.height / 2; context.drawImage(this, destX, destY); }; imageObj.src = "css.png";
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let imageObj = new Image(); imageObj.onload = function(){ let destX = canvas.width / 2 - this.width / 2; let destY = canvas.height / 2 - this.height / 2; context.drawImage(this, destX, destY); };<!-- w w w . d e m o 2 s . c o m--> imageObj.src = "css.png"; </script> </body> </html> First we created a blank DOM object for a HTML <img> element by using the Image class. Then setting the src attribute to the path of a valid image file, you load that image into the image object just as if you set the src attribute of an actual HTML <img> element. This effectively creates a normal HTML img element, but without displaying it in the browser. Or we can assign the value of the image variable to the DOM object of an existing HTML img element. let image = document.getElementById("myImage"); image.onload = function(){ let destX = canvas.width / 2 - this.width / 2; let destY = canvas.height / 2 - this.height / 2; context.drawImage(this, destX, destY); };
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); image.onload = function(){ let destX = canvas.width / 2 - this.width / 2; let destY = canvas.height / 2 - this.height / 2; context.drawImage(this, destX, destY); };<!-- w w w . de m o 2 s .c o m--> </script> </body> </html>

HTML Canvas Resizing images

To resize an image, you pass the width and height at which you want the image to be drawn. The drawImage method with the arguments for resizing looks like this: context.drawImage(image, x, y, width, height); By changing the drawImage method in the previous example to the following. context.drawImage(image, 0, 0, 500, 333);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); image.onload = function(){<!-- w w w . de m o 2 s . c o m --> context.drawImage(image, 0, 0, 500, 333); }; </script> </body> </html> You've used 500 pixels for the width, as that is the width of the canvas.

HTML Canvas Cropping images

Cropping is to cut something to a smaller size. The drawImage() method for cropping uses a total of nine arguments: the source image, the (x, y) coordinate origin of the crop on the source image, the width and height of the crop on the source image, the (x, y) coordinate origin to draw the image on the canvas (the destination), and the width and height to draw the image on the canvas. context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
canvas-image-resize.png

By putting this into practice you can crop out a small area of the image you used earlier and draw it onto the canvas: context.drawImage(image, 0, 0, 50, 50, 0, 0, 50, 50); <!DOCTYPE html>/* w ww . d e m o2 s. c o m */ <html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); image.onload = function(){ context.drawImage(image, 0, 0, 50, 50, 0, 0, 50, 50); }; </script> </body> </html> You can also resize the cropped image as you draw in onto the canvas, like so: context.drawImage(image, 0, 0, 50, , 0, 0, 250, 250);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); image.onload = function(){<!-- w w w . d e m o 2 s .c o m --> context.drawImage(image, 0, 0, 50, 50, 0, 0, 250, 250); }; </script> </body> </html>

HTML Canvas Transforming images

Translation

let image = document.getElementById("myImage"); context.translate(100, 100); image.onload = function(){ context.drawImage(image, 0, 0); };
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); context.translate(100, 100);<!-- w w w . d e m o 2 s . co m --> image.onload = function(){ context.drawImage(image, 0, 0); }; </script> </body> </html>

Rotation

Rotating an image has previously been hard to achieve within the browser. context.translate(250, 250); context.rotate(0.7854); // Rotate 45 degrees image.onload = function(){ context.drawImage(image, 0, 0); };
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); context.translate(50, 50);<!-- w w w . d e mo 2s .c o m--> context.rotate(0.7854); // Rotate 45 degrees image.onload = function(){ context.drawImage(image, 0, 0); }; </script> </body> </html>

Scaling and flipping

We can flip the same image in various ways. let image = document.getElementById("myImage"); context.translate(50, 50);/* w w w . d em o2 s . c o m */ context.rotate(0.7854); // Rotate 45 degrees image.onload = function(){ // Top left context.translate(50, 50); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Bottom left // Reset the transformation matrix context.setTransform(1, 0, 0, 1, 0, 0); context.translate(50, 450); context.scale(1, -1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Bottom right context.setTransform(1, 0, 0, 1, 0, 0); context.translate(450, 450); context.scale(-1, -1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Top right context.setTransform(1, 0, 0, 1, 0, 0); context.translate(450, 50); context.scale(-1, 1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); };
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> <img id='myImage' src='css.png'> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); let canvas = document.getElementById("canvas"); let image = document.getElementById("myImage"); context.translate(50, 50);<!-- w w w . d e m o 2 s . c o m --> context.rotate(0.7854); // Rotate 45 degrees image.onload = function(){ // Top left context.translate(50, 50); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Bottom left // Reset the transformation matrix context.setTransform(1, 0, 0, 1, 0, 0); context.translate(50, 450); context.scale(1, -1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Bottom right context.setTransform(1, 0, 0, 1, 0, 0); context.translate(450, 450); context.scale(-1, -1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); // Top right context.setTransform(1, 0, 0, 1, 0, 0); context.translate(450, 50); context.scale(-1, 1); context.drawImage(image, 0, 0, 500, 500, 0, 0, 200, 200); }; </script> </body> </html>

HTML Canvas Reverse the color values of an image

We can reverse the color values of an image. We subtract the existing color value of a pixel (150), from 255 to reverse, or invert, the color (255-150=105). let image = new Image(); image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; let numPixels = pixels.length; context.clearRect(0, 0, canvas.width(), canvas.height()); for (let i = 0; i < numPixels; i++) { pixels[i*4] = 255-pixels[i*4]; // Red pixels[i*4+1] = 255-pixels[i*4+1]; // Green pixels[i*4+2] = 255-pixels[i*4+2]; // Blue };// w w w . d e m o2 s . c o m context.putImageData(imageData, 0, 0); }); The first few lines create a new Image object and load in the example image. You draw the image to the canvas and store the ImageData object containing all the pixels in a variable. Once you've got the pixels stored, you clear the canvas and start a loop that runs for as many times as there are pixels in the original image. Within the loop you access the pixels and subtract the current values from 255. You don't need to do anything with the alpha value. The last thing to do is draw the pixels back onto the canvas.
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Inverting let image = new Image();<!-- w w w . d e m o 2s . c o m --> image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; let numPixels = pixels.length; // Clear the image context.clearRect(0, 0, canvas.width(), canvas.height()); // Access and change pixel values for (let i = 0; i < numPixels; i++) { pixels[i*4] = 255-pixels[i*4]; // Red pixels[i*4+1] = 255-pixels[i*4+1]; // Green pixels[i*4+2] = 255-pixels[i*4+2]; // Blue }; // Draw image data to the canvas context.putImageData(imageData, 0, 0); }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html>

HTML Canvas Image Grayscale

Grayscale is the conversion of a color image into one that uses shades of gray. The following code accesses and changes the color values. for (let i = 0; i < numPixels; i++) { let average = (pixels[i * 4]+pixels[i * 4+1]+pixels[i * 4+2])/3; pixels[i*4] = average; // Red pixels[i*4+1] = average; // Green pixels[i*4+2] = average; // Blue };
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Grayscale let image = new Image();<!-- w ww .d e m o2 s . c o m--> image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; let numPixels = pixels.length; // Clear the image context.clearRect(0, 0, canvas.width(), canvas.height()); // Access and change pixel values for (let i = 0; i < numPixels; i++) { let average = (pixels[i * 4]+pixels[i * 4+1]+pixels[i * 4+2])/3; pixels[i*4] = average; // Red pixels[i*4+1] = average; // Green pixels[i*4+2] = average; // Blue }; // Draw image data to the canvas context.putImageData(imageData, 0, 0); }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html> Converting colors into grayscale requires you to find the average of the existing color values, by adding them all together and dividing by the number of colors. You use the averaged color as the value for all three colors; red, green, and blue. The result will be a shade of gray for each color.

HTML Canvas Image Pixelation

Pixelation allows you to make part of an image unrecognizable. You split an image into a grid and either average the colors within each segment, or pick a color within each segment. let image = new Image(); image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; context.clearRect(0, 0, canvas.width(), canvas.height()); let numTileRows = 20; let numTileCols = 20; let tileWidth = imageData.width/numTileCols; let tileHeight = imageData.height/numTileRows; for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { };/* w w w . de m o 2 s . c om */ }; });
Open in separate window
<html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); let image = new Image();<!-- w w w . d e m o 2 s . c o m --> image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; // Clear the image context.clearRect(0, 0, canvas.width(), canvas.height()); // Number of tiles let numTileRows = 20; let numTileCols = 20; // Dimensions of each tile let tileWidth = imageData.width/numTileCols; let tileHeight = imageData.height/numTileRows; // Loop through each tile for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { let x = (c*tileWidth)+(tileWidth/2); let y = (r*tileHeight)+(tileHeight/2); // Use Math.floor to convert the pixel positions to integers let pos = (Math.floor(y) * (imageData.width*4))+(Math.floor(x) * 4); let red = pixels[pos]; let green = pixels[pos+1]; let blue = pixels[pos+2]; context.fillStyle = "rgb("+red+", "+green+", "+blue+")"; // Draw the pixelated rectangle context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight); }; }; }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html> You're going to use the second method to grab a color for the pixelated effect, picking a single color within each tile. The simplest way to do this is to use the pixel at the centre of the tile, which you can work out by adding the following code inside the second loop. let x = (c*tileWidth)+(tileWidth/2); let y = (r*tileHeight)+(tileHeight/2); let pos = (Math.floor(y) * (imageData.width * 4))+(Math.floor(x)*4);

HTML Canvas Using Video Images

We can use a video element as the source of the image for the drawImage() method. When we do this, we take a snapshot of the video. The following code provides a demonstration using video as the source for the drawImage() element. let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("vid"); document.getElementById("pressme").onclick = function(e) { ctx.drawImage(imageElement, 0, 0, 360, 240); }
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <video id="vid" src="radian.webm" controls preload="auto" width="360" height="240"> Video cannot be displayed<!-- w w w . d e mo 2 s . c o m --> </video> <div> <button id="pressme">Snapshot</button> </div> <canvas id="canvas" width="360" height="240"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("vid"); document.getElementById("pressme").onclick = function(e) { ctx.drawImage(imageElement, 0, 0, 360, 240); } </script> </body> </html> In this example, we have a <video> element, a <button>, and a <canvas> element. When the button is pressed, the current video frame is used to paint the canvas using the drawImage() method. The following code shows how to use the canvas to display and draw on video. let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("vid"); let width = 100; let height = 10; ctx.lineWidth = 5; ctx.strokeStyle = "red"; setInterval(function() { ctx.drawImage(imageElement, 0, 0, 360, 240); ctx.strokeRect(180 - (width/2),120 - (height/2), width, height); }, 25); setInterval(function() { width = (width + 1) % 200; height = (height + 3) % 200; }, 100);
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <video id="vid" hidden src="radian.webm" preload="auto" width="360" height="240" autoplay></video> <canvas id="canvas" width="360" height="240"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let imageElement = document.getElementById("vid"); let width = 100; let height = 10; ctx.lineWidth = 5;<!-- w w w . d e m o 2 s . c om --> ctx.strokeStyle = "red"; setInterval(function() { ctx.drawImage(imageElement, 0, 0, 360, 240); ctx.strokeRect(180 - (width/2),120 - (height/2), width, height); }, 25); setInterval(function() { width = (width + 1) % 200; height = (height + 3) % 200; }, 100); </script> </body> </html> In this example, there is a video element to which we have applied the hidden attribute, so that it is not visible to the user. We have used two timers - the first fires every 25 milliseconds and draws the current video frame and then a stroked rectangle. The second timer fires every 100 milliseconds and changes the values used for the rectangle. The effect is that the rectangle changes size and is superimposed over the video image.

HTML Canvas Manipulating video

We can pixelate the video. First we set up the html tags for canvas and video tags: <body> <canvas id="myCanvas" width="500" height="281"> <video id="myVideo" width="500" height="281" controls="true"> <source src="radian.mp4" type="video/mp4"></source> <source src="radian.ogg" type="video/ogg"></source> </video> </canvas> <div> <button id="play">Play</button> <button id="stop">Stop</button> </div> </body> Then we use jQuery to bind action to play and stop video. let video = $("#myVideo"); // Trigger for video play button $("#play").click(function() { video.get(0).play(); }); // Trigger for video stop button $("#stop").click(function() { video.get(0).pause(); }); let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); video.bind("play", function() { drawCanvas(); }); To play the video we need to set up a loop of event to draw the video frame by frame: function drawCanvas() { ... setTimeout(drawCanvas, 30); }; The core part of pixelate the video is listed as follows. It is similar to the logic of adding tiles to an image: // Loop through each tile for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { let x = (c*tileWidth)+(tileWidth/2); let y = (r*tileHeight)+(tileHeight/2); // Use Math.floor to convert the pixel positions to integers let pos = (Math.floor(y) * (imageData.width*4))+(Math.floor(x)*4); let red = pixels[pos]; let green = pixels[pos+1]; let blue = pixels[pos+2]; context.fillStyle = "rgb("+red+", "+green+", "+blue+")"; // Draw the pixelated rectangle context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight); };/* w w w . de m o 2 s . c om */ };
Open in separate window
<html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let video = $("#myVideo"); // Trigger for video play button $("#play").click(function() { video.get(0).play();<!-- w w w .d e m o 2 s. c o m --> }); // Trigger for video stop button $("#stop").click(function() { video.get(0).pause(); }); let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); video.bind("play", function() { drawCanvas(); }); function drawCanvas() { if (video.get(0).paused || video.get(0).ended) return false; context.drawImage(video.get(0), 0, 0, 500, 281); let imageData = context.getImageData(0, 0, canvas.width(), canvas.height()); let pixels = imageData.data; // Clear the image context.clearRect(0, 0, canvas.width(), canvas.height()); // Number of tiles let numTileRows = 36; let numTileCols = 64; // Dimensions of each tile let tileWidth = imageData.width/numTileCols; let tileHeight = imageData.height/numTileRows; // Loop through each tile for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { let x = (c*tileWidth)+(tileWidth/2); let y = (r*tileHeight)+(tileHeight/2); // Use Math.floor to convert the pixel positions // to integers let pos = (Math.floor(y) * (imageData.width * 4))+(Math.floor(x)*4); let red = pixels[pos]; let green = pixels[pos+1]; let blue = pixels[pos+2]; context.fillStyle = "rgb("+red+", "+green+", "+blue+")"; // Draw the pixelated rectangle context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight); }; }; setTimeout(drawCanvas, 30); }; }); </script> </head> <body> <canvas id="myCanvas" width="500" height="281"> <video id="myVideo" width="500" height="281" controls="true"> <source src="radian.mp4" type="video/mp4"></source> <source src="radian.ogg" type="video/ogg"></source> </video> </canvas> <div> <button id="play">Play</button> <button id="stop">Stop</button> </div> </body> </html>

HTML Canvas Accessing pixel values

By accessing the individual pixels of the 2d rendering context, you're able to get information such as the color and alpha value of each pixel. You're also able to rewrite each pixel with a different color value so they look entirely different. To access pixels in canvas, use getImageData(). context.getImageData(x, y, width, height); This method takes four arguments: the (x, y) coordinate origin of the pixel area, the width of the pixel area, and the height of the pixel area.
canvas-pixel.png

getImageData() returns a 2d rendering context ImageData object. This ImageData object contains three attributes: width, the width of the pixel area you're accessing, height, the height of the pixel area, and data, a CanvasPixelArray that contains information about all the pixels in the area that you're accessing. Stored within the data attribute is a CanvasPixelArray, a one-dimensional JavaScript array; each pixel represented by four integer values ranging from 0 to 255 that refer to the red (r), green (g), blue (b), and alpha (a) values. So, the first four entries in the array (0-3) are the color values for the first pixel; the next four entries (4-7) are the color values for the second pixel, and so on. The following code shows how to access the RGBA values for the first pixel in the CanvasPixelArray. let imageData = context.getImageData(0, 0, 3, 3); // 3x3 grid let pixel = imageData.data; // CanvasPixelArray let red = pixel[0]; let green = pixel[1]; let blue = pixel[2]; let alpha = pixel[3];
Open in separate window
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Accessing the first pixel let image = new Image();<!-- w w w . d e m o 2 s . c o m --> image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 500, 333); let imageData = context.getImageData(0, 0, 3, 3); // 3x3 grid let pixel = imageData.data; // CanvasPixelArray let red = pixel[0]; let green = pixel[1]; let blue = pixel[2]; let alpha = pixel[3]; console.log(red); }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html> A CanvasPixelArray has no knowledge of the dimensions of the pixel area that you're accessing. Instead, the array that gets returned is one long set of RGBA color values, equal to the number of pixels in the area multiplied by four (four color values for each pixel). For example, if you accessed a pixel grid with a width and height of three pixels, the CanvasPixelArray would have a length of 36 (3 by 3 by 4); a width and height of 200 would mean a length of 160,000 (200 by 200 by 4), and so on. The order of pixels within a CanvasPixelArray is: the top left pixel is at the start of the array (from positions 0, red, to 3, alpha), and the bottom right pixel is at the end of the array. The pixels go in a left to right direction until they reach the end of a row, then return to the beginning of the next row and go from left to right again. We can use the following formula to get exactly the right pixel that you want from a CanvasPixelArray: let imageData = context.getImageData(0, 0, 3, 3); // 3x3 grid let width = imageData.width; let x = 2;//offset on the canvas let y = 2; let pixelRed = ((y-1)*(width*4))+((x-1)*4); let pixelGreen = pixelRed+1; let pixelBlue = pixelRed+2; let pixelAlpha = pixelRed+3; The following code create a color picker: canvas.click(function(e) { let canvasOffset = canvas.offset(); let canvasX = Math.floor(e.pageX-canvasOffset.left); let canvasY = Math.floor(e.pageY-canvasOffset.top); let imageData = context.getImageData(canvasX, canvasY, 1, 1); let pixel = imageData.data; let pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")"; $("body").css("backgroundColor", pixelColor); });
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); let image = new Image();<!-- w w w. d e m o 2 s . c o m--> image.src = "css.png"; $(image).load(function() { context.drawImage(image, 0, 0, 500, 333); }); canvas.click(function(e) { let canvasOffset = canvas.offset(); let canvasX = Math.floor(e.pageX-canvasOffset.left); let canvasY = Math.floor(e.pageY-canvasOffset.top); let imageData = context.getImageData(canvasX, canvasY, 1, 1); let pixel = imageData.data; let pixelColour = "rgba("+pixel[0]+", "+pixel[1]+", " +pixel[2]+", "+pixel[3]+")"; $("body").css("backgroundColor", pixelColour); }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html>

HTML Canvas Create an image from scratch using pixel data

To create pixels you need to call the createImageData() method. By passing the method a width and height, you'll get returned an ImageData object with all the usual attributes: width, height, and data. The CanvasPixelArray contained in the data attribute holds your new pixels, which are invisible at the moment as they're all set to a transparent black color.

Example

In the next example, you're going to create an ImageData object with an area of 200 by 200 transparent pixels, and then change them all to red. let imageData = context.createImageData(200, 200); let pixels = imageData.data; The pixels variable is just used as a quick and easy way to the access the CanvasPixelArray for the pixels. You want to change every pixel to red, so a for loop is needed that cycles through every single pixel. let numPixels = imageData.width*imageData.height; for (let i = 0; i < numPixels; i++) { pixels[i*4] = 255; // Red pixels[i*4+1] = 0; // Green pixels[i*4+2] = 0; // Blue pixels[i*4+3] = 255; // Alpha }; The numPixels variable holds the number of pixels in the ImageData object, giving you the number of times needed to run the for loop. Within each loop you assign the color values for each pixel. You know each pixel has four color values, so by multiplying the pixel number by four you get the index of the red color value for that pixel in the CanvasPixelArray. You're then able to set the red color value to 255 (full color), green and blue to 0, and the alpha to 255 so it's opaque. putImageData() method takes three or seven arguments: an ImageData object, the (x, y) coordinate origin to draw the pixel data, the (x, y) coordinate origin of something called a dirty rectangle, the width of the dirty rectangle, and its height. context.putImageData(imageData, 0, 0);
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Drawing pixels to the canvas let imageData = context.createImageData(200, 200); let pixels = imageData.data;<!-- w w w . d e m o 2s . c o m--> let numPixels = imageData.width*imageData.height; // Access and change pixel values for (let i = 0; i < numPixels; i++) { pixels[i*4] = 255; // Red pixels[i*4+1] = 0; // Green pixels[i*4+2] = 0; // Blue pixels[i*4+3] = 255; // Alpha }; // Draw image data to the canvas context.putImageData(imageData, 0, 0); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html>

HTML Canvas Randomizing pixels on Image

We can completely randomize the colors. for (let i = 0; i < numPixels; i++) { pixels[i*4] = Math.floor(Math.random()*255); // Red pixels[i*4+1] = Math.floor(Math.random()*255); // Green pixels[i*4+2] = Math.floor(Math.random()*255); // Blue pixels[i*4+3] = 255; // Alpha };
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Randomising pixels let imageData = context.createImageData(200, 200); let pixels = imageData.data;<!-- w w w . d e m o2 s . c o m--> let numPixels = imageData.width*imageData.height; // Access and change pixel values for (let i = 0; i < numPixels; i++) { pixels[i*4] = Math.floor(Math.random()*255); // Red pixels[i*4+1] = Math.floor(Math.random()*255); // Green pixels[i*4+2] = Math.floor(Math.random()*255); // Blue pixels[i*4+3] = 255; // Alpha }; // Draw image data to the canvas context.putImageData(imageData, 0, 0); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html> We can insert a random number between 0 and 255. You want to keep the alpha value as 255, otherwise some of your pixels will be slightly transparent. Note how you're using Math.floor to round down the resulting random number (eg. 150.123 would become 150).

HTML Canvas Creating a mosaic effect for Image

You'll create a mosaic effect by creating an area of new pixels, then splitting it up into a grid and setting each segment of the grid to a random color. The following code sets up the tile size: let imageData = context.createImageData(500, 500); let pixels = imageData.data; // Number of mosaic tiles let numTileRows = 4; let numTileCols = 4; // Dimensions of each tile let tileWidth = imageData.width/numTileCols; let tileHeight = imageData.height/numTileRows; We set up an ImageData object of 500 ' 500 pixels, and store the CanvasPixelArray in a variable. Following those lines are two variables that are being used to declare the number of segments that you want to break the area of pixels into; the amount per row, and the amount per column. From now on we'll refer to segments as tiles. The last two lines calculate the width and height of each tile in pixels, based on the dimensions of the ImageData object, and the number of tiles per row and column. The following code loops through the tiles and changes the pixel color values. for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { // Set the pixel values for each tile let red = Math.floor(Math.random()*255); let green = Math.floor(Math.random()*255); let blue = Math.floor(Math.random()*255); }; }; Then we loop within each tile: // Loop through each tile pixel for (let tr = 0; tr < tileHeight; tr++) { for (let tc = 0; tc < tileWidth; tc++) { // Calculate the true position of the tile pixel let trueX = (c*tileWidth)+tc; let trueY = (r*tileHeight)+tr; // Calculate the position of the current pixel in the array let pos = (trueY * (imageData.width * 4))+(trueX * 4); // Assign the colour to each pixel pixels[pos] = red; pixels[pos+1] = green; pixels[pos+2] = blue; pixels[pos+3] = 255; }; };
Open in separate window
<html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); // Creating a mosaic let imageData = context.createImageData(500, 500); let pixels = imageData.data;<!-- w ww .d e m o2 s . co m --> // Number of mosaic segments let numTileRows = 4; let numTileCols = 4; // Dimensions of each segment let tileWidth = imageData.width/numTileCols; let tileHeight = imageData.height/numTileRows; // Loop through each tile for (let r = 0; r < numTileRows; r++) { for (let c = 0; c < numTileCols; c++) { // Set the pixel values for each tile let red = Math.floor(Math.random()*255); let green = Math.floor(Math.random()*255); let blue = Math.floor(Math.random()*255); // Loop through each tile pixel for (let tr = 0; tr < tileHeight; tr++) { for (let tc = 0; tc < tileWidth; tc++) { // Calculate the true position of the tile pixel let trueX = (c*tileWidth)+tc; let trueY = (r*tileHeight)+tr; // Calculate the position of the current pixel in the array let pos = (trueY * (imageData.width * 4))+(trueX*4); // Assign the colour to each pixel pixels[pos] = red; pixels[pos+1] = green; pixels[pos+2] = blue; pixels[pos+3] = 255; }; }; }; }; // Draw image data to the canvas context.putImageData(imageData, 0, 0); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html>

HTML Canvas Coordinate Translation

Translation is the act of moving the origin of the 2d rendering context from one location to another. In the case of canvas you use the translate method, which actually moves the coordinate origin of the 2d rendering context, rather than moving the objects that you're trying to draw. This is how to call the translate method: context.translate(150, 150); The two arguments are the (x , y) coordinate values that dictate how far to move the origin of the 2d rendering context. The (x , y) coordinate values that you provide are added on to the existing translation of the origin, which is (0, 0) by default. For example, if you performed two translations exactly like above, you'd actually have moved the origin 300 units (0+150+150) in the x direction, and 300 units (0+150+150) in the y direction. By moving the origin of the 2d rendering context, all objects drawn to the canvas will now appear to be moved by the same amount: context.fillRect(150, 150, 100, 100); context.translate(150, 150); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(150, 150, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.fillRect(150, 150, 100, 100); context.translate(150, 150); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(150, 150, 100, 100); </script> </body> </html> Normally the second call to fillRect() would draw a square with an origin point at the coordinate (150, 150), but by performing a translation the square will now appear to have an origin of (300, 300). The red square still has an origin of (150, 150), it just appears to have shifted over another 150 pixels because the origin of the 2d rendering context has moved 150 pixels as well since drawing the black square. If you wanted the red square to appear where the point (150, 150) used to be (where the black square is), you'd simply set its origin as (0, 0): context.translate(150, 150); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(0, 0, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.translate(150, 150); context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(0, 0, 100, 100); </script> </body> </html> This works because you've already translated the 2d rendering context to the position (150, 150), so anything drawn from now on at the point (0, 0) will actually appear to be at the point (150, 150). Every transformation method, including translate(), affects all elements drawn after it has been called. They all act directly on the 2d rendering context, not on the shape you're drawing.

HTML Canvas Scaling

Canvas can scale the 2d rendering context in size. It multiplies the pixel values. context.scale(2, 2); context.fillRect(150, 150, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.scale(2, 2); context.fillRect(150, 150, 100, 100); </script> </body> </html> This example is set to scale the 2d rendering context by a multiple of two in both the x and y directions. The 2d rendering context and all objects drawn onto it are now twice as big. For example, a scale of 2 will effectively mean that 1 pixel now equals 2 pixels; so if you draw something at an x of 150, it will now end up looking like it's at an x of 300. You can combine the scale method with translate. context.save(); context.translate(150, 150); context.scale(2, 2); context.fillRect(0, 0, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.save(); context.translate(150, 150); context.scale(2, 2); context.fillRect(0, 0, 100, 100); </script> </body> </html> In this example you're first saving the state of the canvas, before translating the origin point to (150, 150). You then scale the canvas by two and draw a square at the position (0, 0). Because you've translated the origin of the 2d rendering context to (150, 150), the square will be drawn in the correct position whilst still being scaled. Now anything else you draw from now on will be translated by 150 pixels and scaled by 2 in both directions. Since we saved the drawing state before performing the transformations. We can just restore the drawing state as it was previously. context.restore(); context.fillRect(0, 0, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.save(); context.translate(150, 150); context.scale(2, 2); context.fillRect(0, 0, 100, 100); context.restore(); context.fillRect(0, 0, 100, 100); </script> </body> </html> By restoring the drawing state, anything you draw from then on will appear as if the transformations never happened.

HTML Canvas Rotation

The rotate method accepts the angle in radians that you want to rotate the 2d rendering context by: context.rotate(0.7854); // Rotate 45 degrees (Math.PI/4) context.fillRect(150, 150, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.rotate(0.7854); // Rotate 45 degrees (Math.PI/4) context.fillRect(150, 150, 100, 100); </script> </body> </html> The result of this rotation might not be what you expected. The reason is that the rotate method rotates the 2d rendering context around its (0, 0) point of origin. Because of this the square you've drawn is not being rotated itself; it's actually being drawn onto a canvas that is now at a 45- degree angle. To get this effect you need to translate the origin of the 2d rendering context to the centre of the shape that you're drawing. From here you can perform a rotation on the canvas and then draw your shape at the current position. context.translate(200, 200); // Translate to centre of square context.rotate(0.7854); // Rotate 45 degrees // Draw a square with the centre at the point' of rotation context.fillRect(-50, -50, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.translate(200, 200); // Translate to centre of square context.rotate(0.7854); // Rotate 45 degrees // Draw a square with the centre at the point' of rotation context.fillRect(-50, -50, 100, 100); </script> </body> </html> The order that you perform transformations is incredibly important.

HTML Canvas transformation matrix

All of the transformation methods affect something called the transformation matrix. A transformation matrix is an array of numbers, each of which describes a particular kind of transformation. A matrix is split into a number of columns and rows; in the case of canvas you're using a 3x3 matrix - three columns and three rows.
canvas-transform-matrix.png

For our purposes you can ignore the bottom row as you'll never have to or be able to change its values. The rows that are important are the first and second, which contain number values that you'll later refer to in canvas as a to f. You can see in the illustration that each number value corresponds to a particular transformation. For example, a refers to the scale multiplier in the x direction, while f refers to the translation in the y direction. A new 2d rendering context will contain a fresh transformation matrix, called an identity matrix shown in the following figure.
canvas-identify-matrix.png

This special matrix has every value set to 0, apart from the ones on the main diagonal, the line from top left to bottom right. An identity matrix means that absolutely no transformation is performed. It is important to know what the default values are in a transformation matrix.

Manipulating the transformation matrix

The transform() and setTransform() both manipulate the transformation matrix of the 2d rendering context. We can perform a translation and scale using transform, then draw a square to show it all working: context.transform(2, 0, 0, 2, 150, 150); context.fillRect(0, 0, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.transform(2, 0, 0, 2, 150, 150); context.fillRect(0, 0, 100, 100); </script> </body> </html> The transform() method takes six arguments, one for each value of the transformation matrix; the first representing a, through to the last representing f. In this example you want to scale the canvas so it's double the size; so to do that you set the first and fourth arguments to 2, which are a and d - the x scale and the y scale. And to translate the canvas origin, you set the fifth and sixth arguments, which are e and f - the x translation and the y translation. It is important to understand what each value does in the transformation matrix.

Example

The following code shows how to do a rotation transformation without using the rotate method: context.setTransform(1, 0, 0, 1, 0, 0); // Identity matrix let xScale = Math.cos(0.7854); let ySkew = -Math.sin(0.7854); let xSkew = Math.sin(0.7854); let yScale = Math.cos(0.7854); let xTrans = 200; let yTrans = 200; context.transform(xScale, ySkew, xSkew, yScale, xTrans, yTrans); context.fillRect(-50, -50, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.setTransform(1, 0, 0, 1, 0, 0); // Identity matrix let xScale = Math.cos(0.7854);<!-- w w w . d e m o 2 s . c o m --> let ySkew = -Math.sin(0.7854); let xSkew = Math.sin(0.7854); let yScale = Math.cos(0.7854); let xTrans = 200; let yTrans = 200; context.transform(xScale, ySkew, xSkew, yScale, xTrans, yTrans); context.fillRect(-50, -50, 100, 100); </script> </body> </html> The first thing you're doing here is calling the setTransform() method. Its job is to reset the matrix to the identity matrix and then apply the transformation as described in the six arguments. In this example you're using it to reset the transformation matrix so you can be sure you're working with a clean slate. By creating variables to use in the arguments you can keep things looking cleaner and making a little more sense. transform() method actually multiplies the existing transformation matrix by the values that you supply; it's not simply setting the values of the transformation matrix. There is a cumulative effect. If you called transform multiple times, you'd be applying each transformation to the transformation matrix that results from the last transformation.

HTML Canvas Creating a Clipping Region

The clip() method clip() can create a new clipping region. Once we define a clipping region, only paths that occur inside of the region are shown on the screen. The following code gives a demonstration using a clipping region. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.beginPath(); ctx.rect(0, 0, 500, 140); ctx.fill(); ctx.beginPath(); ctx.rect(100, 20, 300, 100); ctx.clip(); ctx.fillStyle = "red"; ctx.beginPath(); ctx.rect(0, 0, 500, 140); ctx.fill();
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.beginPath();<!-- w w w . d e mo 2 s . c o m --> ctx.rect(0, 0, 500, 140); ctx.fill(); ctx.beginPath(); ctx.rect(100, 20, 300, 100); ctx.clip(); ctx.fillStyle = "red"; ctx.beginPath(); ctx.rect(0, 0, 500, 140); ctx.fill(); </script> </body> </html> The script in this example draws a rectangle that fills the canvas, creates a smaller clipping region and then draws another canvas-filling rectangle.

HTML Canvas Using Shadows

There are four drawing state properties that we can use to add shadows to the shapes and text we draw on the canvas. These properties are described in the following table.
Name Description Returns
shadowBlur Sets the degree of blur in the shadow number
shadowColor Sets the color of the shadow string
shadowOffsetX Sets the x-offset for the shadow number
shadowOffsetY Sets the y-offset for the shadow number
The following code shows how we can apply shadows using these properties. Applying shadows to shapes and text. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3;/* w w w . d e m o 2 s . c o m */ ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowBlur = 5; ctx.shadowColor = "grey"; ctx.strokeRect(250, 20, 100, 100); ctx.beginPath(); ctx.arc(420, 70, 50, 0, Math.PI, true); ctx.stroke(); ctx.beginPath(); ctx.arc(420, 80, 40, 0, Math.PI, false); ctx.fill(); ctx.font = "100px sans-serif"; ctx.fillText("Hello", 10, 100); ctx.strokeText("Hello", 10, 100);
Open in separate window
<html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3;<!-- w ww . de m o 2 s . c o m --> ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowBlur = 5; ctx.shadowColor = "grey"; ctx.strokeRect(250, 20, 100, 100); ctx.beginPath(); ctx.arc(420, 70, 50, 0, Math.PI, true); ctx.stroke(); ctx.beginPath(); ctx.arc(420, 80, 40, 0, Math.PI, false); ctx.fill(); ctx.font = "100px sans-serif"; ctx.fillText("Hello", 10, 100); ctx.strokeText("Hello", 10, 100); </script> </body> </html> This example applies shadows to text, a rectangle, a complete circle and two arcs. The shadows are applied to shapes irrespective of whether they are open, closed, filled, or stroked. By default, the 2d rendering context does not draw shadows because shadowBlur, shadowOffsetX, and shadowOffsetY are set to 0, and shadowColor is set to transparent black. The only way you can make a shadow appear is by changing the opacity of the shadowColor to something non-transparent, while also setting either shadowBlur, shadowOffsetX, or shadowOffsetY to a value that isn't 0: context.shadowBlur = 20; context.shadowColor = "rgb(0, 0, 0)"; context.fillRect(50, 50, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.shadowBlur = 20; context.shadowColor = "rgb(0, 0, 0)"; context.fillRect(50, 50, 100, 100); </script> </body> </html> In this example you've given the shadow a 20 pixel blur and have set its color to a fully opaque black. The offset values for the shadow are kept at their default of 0 pixels in the x direction, and 0 pixels in the y direction. Via the shadowBlur, shadowOffsetX, and shadowOffsetY properties you can create a different drop shadow effect: context.shadowBlur = 0; context.shadowOffsetX = 10; context.shadowOffsetY = 10; context.shadowColor = "rgba(100, 100, 100, 0.5)"; // Transparent grey context.fillRect(200, 50, 100, 100);
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.shadowBlur = 0; context.shadowOffsetX = 10; context.shadowOffsetY = 10; context.shadowColor = "rgba(100, 100, 100, 0.5)"; // Transparent grey context.fillRect(200, 50, 100, 100); </script> </body> </html> By changing the blur to 0 you create a razor-sharp shadow, and by moving the offset just slightly to the right and downward you end up with a drop shadow variant. Shadows in canvas work for any shape that you can draw. context.shadowColor = "rgb(255, 0, 0)"; // Red context.shadowBlur = 50; context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.beginPath(); context.arc(400, 100, 50, 0, Math.PI*2, false); context.closePath(); context.fill();
Open in separate window
<html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.shadowColor = "rgb(255, 0, 0)"; // Red context.shadowBlur = 50;<!-- w w w . d e mo 2 s . c o m--> context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.beginPath(); context.arc(400, 100, 50, 0, Math.PI*2, false); context.closePath(); context.fill(); </script> </body> </html>