Canvas element

Last updated

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap. HTML5 Canvas also helps in making 2D games.

Contents

While the HTML5 canvas offers its own 2D drawing API, it also supports the WebGL API to allow 3D rendering with OpenGL ES.

History

Canvas was initially introduced by Apple for use in their own Mac OS X WebKit component in 2004, [1] powering applications like Dashboard widgets and the Safari browser. Later, in 2005, it was adopted in version 1.8 of Gecko browsers, [2] and Opera in 2006, [3] and standardized by the Web Hypertext Application Technology Working Group (WHATWG) on new proposed specifications for next generation web technologies.[ citation needed ]

Usage

A canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to those of other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of canvas include building graphs, animations, games, and image composition.

Interacting with the canvas involves obtaining the canvas' rendering context, which determines whether to use the canvas API, WebGL, or WebGL2 rendering context.

Example

The following code creates a Canvas element in an HTML page:

<canvasid="example"width="200"height="200"> This text is displayed if your browser does not support HTML5 Canvas. </canvas>

Using JavaScript, you can draw on the canvas:

varexample=document.getElementById('example');varcontext=example.getContext('2d');context.fillStyle='red';context.fillRect(30,30,50,50);

This code draws a red rectangle on the screen.

The Canvas API also provides save() and restore(), for saving and restoring all the canvas context's attributes.

Canvas element size versus drawing surface size

A canvas actually has two sizes: the size of the element itself and the size of the element's drawing surface. Setting the element's width and height attributes sets both of these sizes; CSS attributes affect only the element's size and not the drawing surface.

By default, both the canvas element's size and the size of its drawing surface is 300 screen pixels wide and 150 screen pixels high. In the listing shown in the example, which uses CSS to set the canvas element's size, the size of the element is 600 pixels wide and 300 pixels high, but the size of the drawing surface remains unchanged at the default value of 300 pixels × 150 pixels. When a canvas element's size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element (which may result in surprising and unwanted effects).

Example setting element size and drawing surface size to different values:

<!DOCTYPE html><html><head><title>Canvas element size: 600 x 300,     Canvas drawing surface size: 300 x 150</title><style>body{background:#dddddd;}#canvas{margin:20px;padding:20px;background:#ffffff;border:thininset#aaaaaa;width:600px;height:300px;}</style></head><body><canvasid="canvas">         Canvas not supported         </canvas></body></html>

Canvas versus Scalable Vector Graphics (SVG)

SVG is an alternative approach to drawing shapes in browsers. [4] Unlike canvas, which is raster-based, SVG is vector-based, so that each drawn shape is remembered as an object in a scene graph or Document Object Model, which is subsequently rendered to a bitmap. This means that if attributes of an SVG object are changed, the browser can automatically re-render the scene.

Canvas objects, on the other hand, are drawn in immediate mode. In the canvas example above, the rectangle draw operation modifies the canvas, and its representation as a rectangle is forgotten by the system. If the rectangle's position were to be changed, the canvas would need to be redrawn, including any objects that might have been covered by the rectangle. In the equivalent SVG case, one could simply change the position attributes of the rectangle and the browser would determine how to repaint it. There are additional JavaScript libraries that abstract the canvas model to have svg-like scene capabilities within the canvas element. Multiple canvas layers can also be used, meaning that only specific layers need to be recreated when changes are required.

SVG images are represented in XML, and complex scenes can be created and maintained with XML editing tools.

The SVG scene graph enables event handlers to be associated with objects, so a rectangle may respond to an onClick event. To get the same functionality with canvas, one must manually match the coordinates of the mouse click with the coordinates of the drawn rectangle to determine whether it was clicked.

Conceptually, canvas is a lower-level API upon which higher-level interfaces might be built (for example, SVG support). There are JavaScript libraries that provide partial SVG implementations using canvas for browsers that do not provide SVG but support canvas, such as the browsers in Android 2.x. However, this is not normally the case—they are independent standards. The situation is complicated because there are scene graph libraries for canvas, and SVG has some bitmap manipulation functionality.

Reactions

At the time of its introduction, the canvas element was met with mixed reactions from the web standards community. There have been arguments against Apple's decision to create a new proprietary element instead of supporting the SVG standard. There are other concerns about syntax, such as the absence of a namespace. [5]

Intellectual property over canvas

On March 14, 2007, WebKit developer Dave Hyatt forwarded an email from Apple's Senior Patent Counsel, Helene Plotka Workman, [6] which stated that Apple reserved all intellectual property rights relative to WHATWG's Web Applications 1.0 Working Draft, dated March 24, 2005, Section 10.1, entitled “Graphics: The bitmap canvas”, [7] but left the door open to licensing the patents should the specification be transferred to a standards body with a formal patent policy. This caused considerable discussion among web developers and raised questions concerning the WHATWG's lack of a policy on patents in comparison to the World Wide Web Consortium (W3C)'s explicit favoring of royalty-free licenses. Apple later disclosed the patents under the W3C's royalty-free patent licensing terms. [8] The disclosure means that Apple is required to provide royalty-free licensing for the patent whenever the Canvas element becomes part of a future W3C recommendation created by the HTML working group. [9]

Privacy concerns

Canvas fingerprinting is one of a number of browser fingerprinting techniques for tracking online users that allow websites to identify and track visitors using HTML5 canvas element. The technique received wide media coverage in 2014, [10] [11] [12] [13] after researchers from Princeton University and KU Leuven University described it in their paper The Web never forgets. [14] The privacy concerns regarding canvas fingerprinting center around the fact that even deleting cookies and clearing the cache will not be sufficient for users to avoid online tracking.

Browser support

The element is supported by the current versions of Mozilla Firefox, Google Chrome, Internet Explorer, Safari, Konqueror, Opera [15] and Microsoft Edge. [16]

See also

Related Research Articles

<span class="mw-page-title-main">Document Object Model</span> Convention for representing and interacting with objects in HTML, XHTML, and XML documents

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML or XML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

<span class="mw-page-title-main">HTML</span> HyperText Markup Language

The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the meaning and structure of web content. It is often assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.

SVG is an XML-based vector image format for defining two-dimensional graphics, having support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium since 1999.

An HTML element is a type of HTML document component, one of several types of HTML nodes. The first used version of HTML was written by Tim Berners-Lee in 1993 and there have since been many versions of HTML. The current de facto standard is governed by the industry group WHATWG and is known as the HTML Living Standard.

<span class="mw-page-title-main">Favicon</span> Icon associated with a particular web site

A favicon, also known as a shortcut icon, website icon, tab icon, URL icon, or bookmark icon, is a file containing one or more small icons associated with a particular website or web page. A web designer can create such an icon and upload it to a website by several means, and graphical web browsers will then make use of it. Browsers that provide favicon support typically display a page's favicon in the browser's address bar and next to the page's name in a list of bookmarks. Browsers that support a tabbed document interface typically show a page's favicon next to the page's title on the tab, and site-specific browsers use the favicon as a desktop icon.

Web standards are the formal, non-proprietary standards and other technical specifications that define and describe aspects of the World Wide Web. In recent years, the term has been more frequently associated with the trend of endorsing a set of standardized best practices for building web sites, and a philosophy of web design and development that includes those methods.

In web development, "tag soup" is a pejorative for syntactically or structurally incorrect HTML written for a web page. Because web browsers have historically treated structural or syntax errors in HTML leniently, there has been little pressure for web developers to follow published standards, and therefore there is a need for all browser implementations to provide mechanisms to cope with the appearance of "tag soup", accepting and correcting for invalid syntax and structure where possible.

Cairo (graphics) Vector graphics-based software library

Cairo is an open-source graphics library that provides a vector graphics-based, device-independent API for software developers. It provides primitives for two-dimensional drawing across a number of different back ends. Cairo uses hardware acceleration when available.

<span class="mw-page-title-main">HTML5</span> Fifth and current version of hypertext markup language

HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is the fifth and final major HTML version that is a World Wide Web Consortium (W3C) recommendation. The current specification is known as the HTML Living Standard. It is maintained by the Web Hypertext Application Technology Working Group (WHATWG), a consortium of the major browser vendors.

The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple Inc., the Mozilla Foundation and Opera Software, leading Web browser vendors in 2004.

Extensible HyperText Markup Language (XHTML) is part of the family of XML markup languages. It mirrors or extends versions of the widely used HyperText Markup Language (HTML), the language in which Web pages are formulated.

The HTML5 draft specification adds video and audio elements for embedding video and audio in HTML documents. The specification had formerly recommended support for playback of Theora video and Vorbis audio encapsulated in Ogg containers to provide for easier distribution of audio and video over the internet by using open standards, but the recommendation was soon after dropped.

A web worker, as defined by the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG), is a JavaScript script executed from an HTML page that runs in the background, independently of scripts that may also have been executed from the same HTML page. Web workers are often able to utilize multi-core CPUs more effectively.

Microdata is a WHATWG HTML specification used to nest metadata within existing content on web pages. Search engines, web crawlers, and browsers can extract and process Microdata from a web page and use it to provide a richer browsing experience for users. Search engines benefit greatly from direct access to this structured data because it allows them to understand the information on web pages and provide more relevant results to users. Microdata uses a supporting vocabulary to describe an item and name-value pairs to assign values to its properties. Microdata is an attempt to provide a simpler way of annotating HTML elements with machine-readable tags than the similar approaches of using RDFa and microformats.

The HTML5 specification introduced the video element for the purpose of playing videos, partially replacing the object element. HTML5 video is intended by its creators to become the new standard way to show video on the web, instead of the previous de facto standard of using the proprietary Adobe Flash plugin, though early adoption was hampered by lack of agreement as to which video coding formats and audio coding formats should be supported in web browsers. As of 2020, HTML5 video is the only widely supported video playback technology in modern browsers, with the Flash plugin being phased out.

The Web platform is a collection of technologies developed as open standards by the World Wide Web Consortium and other standardization bodies such as the Web Hypertext Application Technology Working Group, the Unicode Consortium, the Internet Engineering Task Force, and Ecma International. It is the umbrella term introduced by the World Wide Web Consortium, and in 2011 it was defined as "a platform for innovation, consolidation and cost efficiencies" by W3C CEO Jeff Jaffe. Being built on The evergreen Web has allowed for the addition of new capabilities while addressing security and privacy risks. Additionally, developers are enabled to build interoperable content on a cohesive platform.

Modern HTML5 has feature-parity with the now-obsolete Adobe Flash. Both include features for playing audio and video within web pages. Flash was specifically built to integrate vector graphics and light games in a web page, features that HTML5 also supports.

HTML5 Audio is a subject of the HTML5 specification, incorporating audio input, playback, and synthesis, as well as, in the browser. iOS

Google Chrome Experiments Online showroom of web browser based experiments

Google Chrome Experiments is an online showroom of web browser based experiments, interactive programs, and artistic projects. Launched on March 1, 2009, Google Chrome Experiments is an official Google website that was originally meant to test the limits of JavaScript and the Google Chrome browser's performance and abilities. As the project progressed, it took the role of showcasing and experimenting latest open-source web-based technologies, such as JavaScript, HTML5, WebGL, Canvas, SVG, CSS, and some others. All the projects on Chrome experiments are user submitted and are made using open source technologies. As of February 24, 2015, there were 1,000 different Chrome projects posted on the website.

<span class="mw-page-title-main">Boxy SVG</span> Vector graphics editor

Boxy SVG is a vector graphics editor for creating illustrations, as well as logos, icons, and other elements of graphic design. It is primarily focused on editing drawings in the SVG file format. The program is available as both a web app and a desktop application for Windows, macOS, ChromeOS, and Linux-based operating systems.

References

  1. Ian Hixie (2004-07-12). "Extending HTML" . Retrieved 2011-06-13.
  2. Mozilla Developer Connection. "HTMLCanvasElement". Archived from the original on 2011-06-04. Retrieved 2011-06-13.
  3. "Opera 9.0 changelog". Archived from the original on 2012-09-10. Retrieved 2006-06-20.
  4. "Scalable Vector Graphics | CorelDRAW". www.coreldraw.com. Retrieved 2022-09-23.
  5. Ian Hickson remarks regarding canvas and other Apple extensions to HTML
  6. "[whatwg] Web Applications 1.0 Draft, David Hyatt, Wed Mar 14 14:31:53 PDT 2007". Archived from the original on 2007-05-02. Retrieved 2007-05-01.
  7. Web Applications 1.0 Early Working Draft - Dynamic graphics: The bitmap canvas
  8. HTML Working Group Patent Policy Status – Known Disclosures
  9. W3C patent policy in use by HTML working group
  10. Knibbs, Kate (July 21, 2014). "What You Need to Know About the Sneakiest New Online Tracking Tool". Gizmodo . Retrieved July 21, 2014.
  11. Joseph Steinberg (July 23, 2014). "You Are Being Tracked Online By A Sneaky New Technology -- Here's What You Need To Know". Forbes . Retrieved November 15, 2014.
  12. Angwin, Julia (July 21, 2014). "Meet the Online Tracking Device That is Virtually Impossible to Block". ProPublica . Retrieved July 21, 2014.
  13. Kirk, Jeremy (July 21, 2014). "Stealthy Web tracking tools pose increasing privacy risks to users". PC World . Retrieved July 21, 2014.
  14. Acar, Gunes; Eubank, Christian; Englehardt, Steven; Juarez, Marc; Narayanan, Arvind; Diaz, Claudia (July 24, 2014). "The Web never forgets: Persistent tracking mechanisms in the wild" . Retrieved July 24, 2014.
  15. Sucan, Mihai (4 Feb 2010). "SVG or Canvas? Сhoosing between the two". Opera Software. Archived from the original on 23 June 2010. Retrieved 3 May 2010.
  16. "Canvas, Microsoft Edge documentation".