# How to use HTML &lt;canvas&gt; to create a framework for graphics

The HTML `<canvas>` element allows you to create an area where you can add graphics or animations using JavaScript. A 2D context object is created, and with different methods from the `<canvas>` API, you can specify the content you want to display.

## What is the HTML `<canvas>` tag?

HTML `<canvas>` is an element that provides a drawing area where you can create **graphics or animations** using [JavaScript](https://www.ionos.co.uk/digitalguide/websites/web-development/embed-javascript-in-html/). The area is defined by specifying height and width attributes and can be placed anywhere in an [HTML](https://www.ionos.co.uk/digitalguide/websites/web-development/what-is-html/) document using the [HTML tag](https://www.ionos.co.uk/digitalguide/websites/web-development/html-tags/) `<canvas>`.

The content in the `<canvas>` element is not an actual website component, so it’s not possible to style it with [CSS](https://www.ionos.co.uk/digitalguide/websites/web-design/css-coding-made-easy/) or other HTML elements. If a browser doesn’t support HTML `<canvas>` , fallback content that has been included between the opening and closing `<canvas>` tags will be displayed instead. However, modern browsers typically support the element natively.

## What is the syntax of the HTML `<canvas>` tag?

The HTML `<canvas>` element doesn’t offer any built-in design tools. It simply provides a framework where you can use JavaScript to create graphics. The basic syntax of the element is as follows:

```html
<canvas id="ExampleCanvas" width="[in pixels]" height="[in pixels]"></canvas>
```

You name the element using `id` and assign it dimensions using `width` and `height`. Optionally, you can use other parameters to specify the design of the graphic.

## How does `<canvas>` work?

You can use the above syntax to create a simple area whenever you want to. In the example below, the area should have a length of 500 pixels and a height of 250 pixels. Here’s the code:

```html

<html>
<body>
<h1>Example for HTML canvas</h1>
<canvas id="ExampleCanvas" width="500" height="250" style="border: 1px solid grey"></canvas>
<div class="hash d-none" hidden>hash_b88a0e196a561aaaf5a54ababe06ba7d012bad97</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```

This creates a blank canvas. To fill the HTML `<canvas>` element with **shapes, images, text or gradients** (or to animate elements), you’ll need to use JavaScript. The content is stored as pixels in a bitmap, which can be converted into a *PNG* image later.

To use the element, use the `getElementById()` method. This only works if you have assigned a unique ID to the `<canvas>` area. If you want to paint, draw or otherwise interact within the defined area, you must create a **2D context object**. Building on our example for above, this is how the code looks:

```html
const ExampleCanvas = document.getElementById("ExampleCanvas");
const ctx = ExampleCanvas.getContext("2d");
```

Now, we can use the HTML `<canvas>` element as a canvas. We’ll start by placing a simple rectangle in the defined area using the `fillRect()` function. This should be in teal and be 200 pixels wide and 150 pixels high. We’re going to place it 10 pixels from the left edge and 50 pixels from the top edge. Here’s the code:

```html

<html>
<body>
<h1>Example for HTML canvas</h1>
<canvas id="ExampleCanvas" width="500" height="250" style="border:1px solid grey"></canvas>
<script>
const ExampleCanvas = document.getElementById("ExampleCanvas");
const ctx = ExampleCanvas.getContext("2d");
ctx.fillStyle = "teal";
ctx.fillRect(10, 50, 200, 150);
</script>
<div class="hash d-none" hidden>hash_b88a0e196a561aaaf5a54ababe06ba7d012bad97</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```

## What can HTML `<canvas>` be used for?

Although we only drew a simple rectangle in our example above, you can also use the `<canvas>` element to create much more complex shapes and designs. For example, you can create **arcs, texts, transparencies, colour gradients and graphics** in *GIF*, *JPEG* and *PNG* formats. These can be cropped, scaled and positioned as well. You can also use the JavaScript time function to implement animations in an HTML `<canvas>` tag.

## What dimensions can a `<canvas>` element have?

The maximum dimensions for an HTML `<canvas>` element vary depending on the browser and environment. For example, the limit on iOS is 4096 x 4096 pixels, while other systems may allow sizes exceeding 10,000 x 10,000 pixels. The canvas area automatically **adjusts to maintain aspect ratios**, making it responsive and suitable for different devices.

## HTML `<canvas>` API methods

Earlier in the article, we took a look at how to create a 2D context object. Using `getContext("2d")`, you can fill the `<canvas>` area at any time. Below we have summarised the most important methods available in the API.

### Text

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`font`</td>
      <td>Defines the font for text</td>
    </tr>
    <tr>
      <td>`fillText()`</td>
      <td>Inserts text (completely filled in) in the HTML `<canvas>`</td>
    </tr>
    <tr>
      <td>`strokeText()`</td>
      <td>Inserts text (outlines only)</td>
    </tr>
  </tbody>
</table>

### Image

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`drawImage()`</td>
      <td>Places an image or video in an HTML `<canvas>` element</td>
    </tr>
  </tbody>
</table>

### Drawing

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`fillRect()`</td>
      <td>Draws a filled rectangle</td>
    </tr>
    <tr>
      <td>`strokeRect()`</td>
      <td>Draws an empty rectangle</td>
    </tr>
    <tr>
      <td>`clearRect()`</td>
      <td>Clears specified pixels within a rectangle</td>
    </tr>
  </tbody>
</table>

### Path

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`beginPath()`</td>
      <td>Starts a new path</td>
    </tr>
    <tr>
      <td>`lineTo()`</td>
      <td>Draws a line to the path</td>
    </tr>
    <tr>
      <td>`moveTo()`</td>
      <td>Moves the path to a specific point within the canvas</td>
    </tr>
  </tbody>
</table>

### Design

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`addColorStop()`</td>
      <td>Specifies a colour and a position in a gradient object</td>
    </tr>
    <tr>
      <td>`createLinearGradient()`</td>
      <td>Creates a linear gradient object</td>
    </tr>
    <tr>
      <td>`createPattern()`</td>
      <td>Repeats the specified element</td>
    </tr>
    <tr>
      <td>`shadowBlur`</td>
      <td>Sets or returns the blur level for shadows</td>
    </tr>
    <tr>
      <td>`shadowColor`</td>
      <td>Sets or returns the colour to use for shadows</td>
    </tr>
  </tbody>
</table>

### Additional functions

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`restore()`</td>
      <td>Restores the state of a drawing context to the last time it was saved</td>
    </tr>
    <tr>
      <td>`save()`</td>
      <td>Saves the current status and all its attributes</td>
    </tr>
  </tbody>
</table>

## HTML `<canvas>` example with text and colour gradient

In our final example, we’ll use some of the methods that we looked at in the last section. First, we’re going to create a frame with the dimensions **500 x 250 pixels** using the HTML `<canvas>` tag. Then we’re going to create a **2D context object**. Lastly, we’ll insert a headline and an additional sentence with a colour gradient. Here’s the code:

```html

<html>
<body>
<h1>Example for HTML canvas with text and colour gradient</h1>
<h2>This example uses the strokeText() and gradient methods.</h2>
<canvas id="ExampleCanvas" width="500" height="250" style="border:1px solid grey"></canvas>
<script>
const c = document.getElementById("ExampleCanvas");
const ctx = c.getContext("2d");
ctx.font = "40px Calibri";
ctx.strokeText("This is a headline", 20, 50);
ctx.font = "30px Calibri";
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "teal");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "green");
ctx.strokeStyle = gradient;
ctx.strokeText("Here is an additional sentence", 20, 90);
</script>
<div class="hash d-none" hidden>hash_b88a0e196a561aaaf5a54ababe06ba7d012bad97</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```


This is a markdown version of: [https://www.ionos.co.uk/digitalguide/websites/web-development/html-canvas/](https://www.ionos.co.uk/digitalguide/websites/web-development/html-canvas/) for AI/LLM consumption.