YouTip LogoYouTip

Att Canvas Width

## HTML <canvas> width Attribute The `width` attribute of the `` element specifies the width of the drawing area in pixels. It is crucial to distinguish between the canvas's **drawing buffer width** (set via this HTML attribute) and its **display size** (set via CSS). This tutorial covers how to use the `width` attribute correctly, how it behaves, and how to avoid common pitfalls. --- ## Syntax ```html ``` ### Attribute Values | Value | Description | | :--- | :--- | | *pixels* | Specifies the width of the canvas in pixels (e.g., `width="200"`).
**Default value is 300.** | --- ## Browser Support | Attribute | Chrome | Edge/IE | Firefox | Safari | Opera | | :--- | :--- | :--- | :--- | :--- | :--- | | `width` | Yes | 9.0+ | Yes | Yes | Yes | *Note: The `` element and its attributes are not supported in Internet Explorer 8 and earlier versions.* --- ## Code Examples ### Example 1: Basic Canvas Setup This example creates a canvas element with a width and height of 200 pixels and a simple border applied via inline CSS. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Clearing the Canvas Dynamically Whenever a canvas's `width` or `height` attribute is reassigned (even to its current value), the canvas coordinate system is reset, and all drawn content is cleared. You can leverage this behavior in JavaScript to quickly clear the canvas. ```html Clearing Canvas Example Your browser does not support the HTML5 canvas tag.

``` --- ## Important Considerations ### 1. HTML Attribute vs. CSS Styling It is highly recommended to set the canvas dimensions using the HTML `width` and `height` attributes rather than CSS. * **HTML Attributes (`width`/`height`):** Set the actual resolution of the canvas's drawing buffer. If you do not specify these, the canvas defaults to **300px wide by 150px high**. * **CSS Properties (`width`/`height`):** Set the size of the element box in which the canvas is displayed. If you set the canvas size only with CSS (e.g., `style="width: 600px; height: 300px;"`) without setting the HTML attributes, the browser will take the default 300x150 drawing buffer and stretch/scale it to fit the 600x300 CSS box. This results in blurry, pixelated, or distorted graphics. ### 2. State Reset on Width Change Modifying the `width` property via JavaScript resets the canvas context. This means: * All drawings are erased. * The coordinate system is reset to the origin `(0,0)`. * Any context styles (such as `fillStyle`, `strokeStyle`, `lineWidth`, or transformations) are reset to their default values.
← Att Caption AlignAtt Canvas Height β†’