search
HomeWeb Front-endJS TutorialHTML5 Canvas Tutorial: An Introduction

HTML5 Canvas Tutorial: An Introduction

Key Takeaways

  • HTML5 Canvas is a powerful technology that allows developers to draw graphics and create animations directly within a browser using JavaScript. The canvas element is defined in HTML code using width and height attributes, and its real power is harnessed through the HTML5 Canvas API.
  • The HTML5 Canvas feature is interactive, capable of animation, flexible, and supported by all major browsers. It can be used for a range of applications including gaming, advertising, data representation, education and training, and art and decoration.
  • To use HTML5 Canvas, a developer needs a code editor and a browser with HTML5 canvas support. A canvas element is created in HTML, and JavaScript is used to access the canvas area through a full set of drawing functions, enabling the generation of dynamic graphics.
  • HTML5 Canvas has a unique coordinate system where the origin is placed at the upper-left corner of the canvas. X coordinates increase to the right and Y coordinates increase towards the bottom of the canvas. This system does not have visible negative points, so objects positioned using negative coordinate points will not appear on the page.

Interested in CSS animation? Check out Creating Animations with CSS, a complete course on CSS Transitions and Keyframes animation by expert web developer Donovan Hutchinson, available for SitePoint members. For a sample of HTML5 canvas animations, watch Illustrations with the HTML5 Canvas below, it’s one video in our Start Animating with the HTML5 Canvas mini course.

Loading the player…

One of the most important instruments in a painter’s toolkit is their canvas. It gives them the freedom to express all kinds of feelings, impressions, ideas, and so forth, in almost unlimited variations and combinations. And that freedom can be restricted only by two things — their skill level and their imagination.

The situation in the web development world is similar. With the ongoing progress of HTML5 and its powerful specifications, web developers have gained the ability to do things that were impossible in the past. Drawing graphics and creating animations directly in the browser is now completely possible thanks to a technology called HTML5 Canvas.

What is HTML5 Canvas?

The canvas element is an element defined in HTML code using width and height attributes. The real power of the canvas element, however, is accomplished by taking advantage of the HTML5 Canvas API. This API is used by writing JavaScript that can access the canvas area through a full set of drawing functions, thus allowing for dynamically generated graphics.

What’s so Great About HTML5 Canvas?

Here are some reasons you might want to consider learning to use HTML5’s canvas feature:

  • Interactivity. Canvas is fully interactive. It can respond to a user’s actions by listening for keyboard, mouse, or touch events. So a developer is not restricted to only static graphics and images.
  • Animation. Every object drawn on the canvas can be animated. This allows for all levels of animations to be created, from simple bouncing balls to complex forward and inverse kinematics.
  • Flexibility. Developers can create just about anything using canvas. It can display lines, shapes, text, images, etc. — with or without animation. Plus, adding video and/or audio to a canvas application is also possible.
  • Browser/Platform Support. HTML5 Canvas is supported by all major browsers and can be accessed on a wide range of devices including desktops, tablets, and smart phones.
  • Popularity. Canvas popularity is rapidly and steadily growing so there is no shortage of resources available.
  • It’s a web standard. Unlike Flash and Silverlight, Canvas is open technology that’s part of HTML5. And although not all of its features are implemented in all browsers, developers can be certain canvas will be around indefinitely.
  • Develop once, run everywhere. HTML5 Canvas offers great portability. Once created, Unlike Flash and Silverlight, a canvas application can run almost anywhere — from the largest computers to the smallest mobile devices.
  • Free and accessible development tools. The basic tools for creating HTML5 canvas applications are just a browser and a good code editor. Plus, there are many great and free libraries and tools to help developers with advanced canvas development.

What Applications Can You Create with HTML5 Canvas?

OK, canvas is great. But what exactly can use it for? Let’s see.

  • Gaming. The HTML5 Canvas’ feature set is an ideal candidate for producing all sorts of 2D and 3D games.
  • Advertising. HTML5 Canvas is a great replacement for Flash-based banners and ads. It has all the needed features for attracting buyers’ attention.
  • Data Representation. HTML5 can collect data from global data sources and use it to generate visually appealing and interactive graphs and charts with the canvas element.
  • Education and Training. HTML5 canvas can be used to produce effective and attractive learning experiences, combining text, images, videos, and audio.
  • Art and Decoration. With a little bit of imagination and canvas’s wide variety of colors, gradients, patterns, transparency, shadows, and clipping features, all kinds of artistic and decorative graphics can be drawn.

Now that we know why we should learn canvas, let’s look at the basics of HTML5 Canvas and how to start using it.

Canvas Rendering Contexts

Every HTML5 canvas element must have a context. The context defines what HTML5 Canvas API you’ll be using. The 2d context is used for drawing 2D graphics and manipulating bitmap images. The 3d context is used for 3D graphics creation and manipulation. The latter is actually called WebGL and it’s based on OpenGL ES.

Getting Started

To get started with canvas, all you need is a code editor and a browser with HTML5 canvas support. I use Sublime Text and Google Chrome, but you can use whatever you want.

Our HTML to start will look like this:

<span><span><span><canvas> id<span>="exampleCanvas"</span> width<span>="500"</span> height<span>="300"</span>></canvas></span>
</span>
  <span><!-- OPTION 1: leave a message here if browser doesn't support canvas -->
</span>    <span><span><span><p>></p></span>Your browser doesn’t currently support HTML5 Canvas. 
</span>    Please check caniuse.com/#feat=canvas for information on 
    browser support for canvas.<span><span><span></span>></span>
</span>
  <span><!-- OPTION 2: put fallback content (text, image, Flash, etc.) 
</span><span >                 if the browser doesn't support canvas -->
</span>
<span><span><span></span>></span></span></span></span>

And here is our JavaScript, which we can include at the bottom of our HTML page:

<span>var canvas = document.getElementById('exampleCanvas'),
</span>    context <span>= canvas.getContext('2d');
</span>
    <span>// code examples will continue here...</span>

By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels, even if these aren’t specified in the HTML. You can change the size by specifying the width and height, as I’ve done in the HTML.

Notice also that we’ve given the canvas an id attribute that we’ll use in our JavaScript. And finally, if you want, you can use CSS to add a border to make the canvas visible by means of a thin frame. This is not required, it’s used as a visual aid for us to see the boundary of the canvas element.

Notice that between the opening and closing tags, I’ve added content that will be displayed if the browser doesn’t support canvas. This can be just about any type of content that an older browser supports.

The JavaScript starts with two lines. In the first line we create a variable that caches our canvas element via its ID. The second line creates a variable (context) that references the 2D context for the canvas using the getContext() function. We’ll use the context variable to access all canvas drawing functions and properties.

With our canvas ready to go we can start experimenting with the Canvas API. But before that, let’s clarify a few more aspects of the canvas feature.

HTML5 Canvas Element Size vs. Drawing Surface Size

Besides the canvas element’s width and height attributes, you can also use CSS to set the size of a canvas element. However, sizing a canvas element with CSS is not the same as setting the element’s width and height attributes. This is because a canvas actually has two sizes: the size of the element itself and the size of the element’s drawing surface.

When you set the element’s width and height attributes, you set both the element’s size and the size of the element’s drawing surface; however, when you use CSS to size a canvas element, you set only the element’s size and not the drawing surface. When the canvas element’s size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element.

Because of this, it’s a good idea to use the canvas element’s width and height attributes to size the element, instead of using CSS.

Understanding the Canvas Coordinate System

In a 2D space, positions are referenced using X and Y coordinates. The X axis extends horizontally, and the Y axis extends vertically. The center has a position x = 0 and y = 0, that can also be expressed as (0, 0). This method of positioning objects, used in mathematics, is known as the Cartesian coordinate system.

The Canvas coordinate system, however, places the origin at the upper-left corner of the canvas, with X coordinates increasing to the right and Y coordinates increasing toward the bottom of the canvas. So unlike a standard Cartesian coordinate space, the Canvas space doesn’t have visible negative points. Using negative coordinates won’t cause your application to fail, but objects positioned using negative coordinate points won’t appear on the page.

HTML5 Canvas Tutorial: An Introduction

Basic Canvas Examples

As mentioned, HTML5 Canvas let’s you create many types of objects, including lines, curves, paths, shapes, text, etc. In the examples to follow you can see how some of these objects are actually drawn. I won’t go in extensive detail on the Canvas API; these are just some easy to help you get a feel for how canvas works.

Drawing Lines

To draw a line, we use four canvas API methods. We start with the beginPath() method which instructs the browser to prepare to draw a new path. Next, we use the moveTo(x, y) method to set the line’s starting point. Then lineTo(x, y) method sets the ending point and draws the line by connecting the two points.

At this point the line will be drawn, but it’s still invisible. To make it visible we use the stroke() method to display the line with the default black color.

<span><span><span><canvas> id<span>="exampleCanvas"</span> width<span>="500"</span> height<span>="300"</span>></canvas></span>
</span>
  <span><!-- OPTION 1: leave a message here if browser doesn't support canvas -->
</span>    <span><span><span><p>></p></span>Your browser doesn’t currently support HTML5 Canvas. 
</span>    Please check caniuse.com/#feat=canvas for information on 
    browser support for canvas.<span><span><span></span>></span>
</span>
  <span><!-- OPTION 2: put fallback content (text, image, Flash, etc.) 
</span><span >                 if the browser doesn't support canvas -->
</span>
<span><span><span></span>></span></span></span></span>

See the Pen Canvas Line Example by SitePoint (@SitePoint) on CodePen.

Draw Rectangle

To draw a rectangle, we can use the fillRect(x, y, width, height) method to set the coordinates and the dimensions, along with the fillStyle property to set the fill color.

<span>var canvas = document.getElementById('exampleCanvas'),
</span>    context <span>= canvas.getContext('2d');
</span>
    <span>// code examples will continue here...</span>

See the Pen Canvas Rectangle Example by SitePoint (@SitePoint) on CodePen.

Notice that the rectangle is positioned near the top left corner.

Draw Text

To draw text on the canvas, we can use fillText(string, x, y) along with the font property to set the font, size, and style of the text (similar to font shorthand in CSS).

context<span>.beginPath();
</span>context<span>.moveTo(50, 50);
</span>context<span>.lineTo(250, 150);
</span>context<span>.stroke();</span>

See the Pen Canvas Text Example by SitePoint (@SitePoint) on CodePen.

You should be aware that although simple drawing with the HTML5 Canvas API is easy, creating complex shapes and animations requires some Maths and Physics knowledge. One of the best books on this topic is Foundation HTML5 Animation with JavaScript. This book is a great resource for learning to move things, from simple to complex animations.

Where to Learn More?

If you want to learn here are some resources:

  • Canvas tutorial – An excellent tutorial on MDN, full of examples, illustrations, and detailed explanations.
  • HTML5 Canvas Element Guide – A beginner’s tutorial from Six Revisions.
  • HTML5 Canvas tutorials – A full set of tutorials created by Eric Rowell, the creator of the KineticJS canvas library. All examples are interactive; you can play with them and see the result immediately.

Speed Up Canvas Development

Working with the “raw” HTML5 Canvas API can be a tedious job. That’s why it’s a good idea when you learn it well to switch to a good canvas library that can speed up and make your canvas development a lot easier.

Here are some popular choices:

  • KineticJS
  • Paper.js
  • EaselJS
  • Fabric.js
  • oCanvas

Another way to speed up your HTML5 Canvas development is by using the Ai->Canvas plugin for Adobe Illustrator. You can find an overview of the plugin in this article on SitePoint.

Conclusion

That’s it. I hope this introductory HTML5 Canvas tutorial has given you a good starting point from which to continue your learning and exploring of this powerful technology.

Frequently Asked Questions (FAQs) about HTML5 Canvas

What is the difference between SVG and HTML5 Canvas?

SVG (Scalable Vector Graphics) and HTML5 Canvas are both web technologies used to create graphics. However, they differ in their approach and use cases. SVG is a vector-based approach where each drawn shape is remembered as an object. If attributes of an object are changed, the browser can automatically re-render the scene. SVG is great for interactive graphics and animations of elements. On the other hand, HTML5 Canvas is pixel-based. Once a shape is drawn, it is forgotten by the system. If its attributes change, it must be redrawn along with the entire scene. This makes Canvas ideal for graphic-intensive games or applications like photo editing software.

How can I add text to a Canvas?

Adding text to a Canvas is straightforward. You can use the fillText(text, x, y) method, where text is the string that you want to write, and x and y are the coordinates where the text will start. You can also customize the font, size, and color of the text using the font and fillStyle properties.

Can I use HTML5 Canvas for game development?

Yes, HTML5 Canvas is a popular choice for 2D game development. Its pixel-based nature makes it suitable for creating complex and graphic-intensive games that run smoothly in the browser. However, for 3D games, WebGL, which also uses the Canvas API, would be a better choice due to its hardware acceleration capabilities.

How can I draw shapes with HTML5 Canvas?

HTML5 Canvas provides several methods to draw shapes. For example, to draw a rectangle, you can use the fillRect(x, y, width, height) method. To draw a circle, you can use the arc(x, y, radius, startAngle, endAngle) method. You can also draw complex shapes using paths.

How can I animate objects with HTML5 Canvas?

Animation in HTML5 Canvas is achieved by redrawing the entire canvas at a high rate, typically 60 times per second. Each redraw is called a frame, and changes to the objects’ properties are made between frames to create the illusion of movement. This is typically done using the requestAnimationFrame() method.

Can I interact with objects drawn on the Canvas?

Unlike SVG, HTML5 Canvas does not remember objects once they are drawn. This means you cannot attach event handlers to them directly. However, you can achieve interactivity by keeping track of the objects’ properties in JavaScript and redrawing the canvas when an interaction occurs.

How can I save the Canvas content as an image?

You can save the content of a Canvas as an image using the toDataURL() method. This method returns a data URL containing a representation of the image in the format specified by the type parameter (defaults to PNG).

How can I clear the Canvas?

You can clear the entire Canvas using the clearRect(x, y, width, height) method. To clear the entire canvas, you can set x and y to 0, and width and height to the width and height of the canvas.

Can I use HTML5 Canvas in all browsers?

HTML5 Canvas is supported in all modern browsers, including Chrome, Firefox, Safari, Opera, and Edge. However, it is not supported in Internet Explorer 8 or earlier.

How can I handle errors in HTML5 Canvas?

Error handling in HTML5 Canvas is typically done using try-catch blocks in JavaScript. However, since Canvas is a low-level API, it does not provide detailed error messages. Therefore, debugging can be challenging and often involves a lot of trial and error.

The above is the detailed content of HTML5 Canvas Tutorial: An Introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment