Web HTMLCanvasElement API | Canvas Element width property
In Web API there is a canvas element which has an attribute of width which represents the width of the canvas in CSS pixels. There is a HTMLCanvasElement.width property by which we can fetch this width attribute from canvas element, which is a positive integer.
Syntax:
var widthVal = canvas.width; canvas.width = widthVal;
Note: If the width attribute value is not provided or is set to undefined value, like a negative value then the default value is set to 300.
Example 1: width attribute set to 500
<!DOCTYPE html> <html> <head> <style> a:focus { background-color: magenta; } </style> <canvas id="canvas" width="500" height="300"></canvas> <script type="text/javascript"> function getwidth() { var canvas = document.getElementById('canvas'); document.getElementById('width').innerHTML = canvas.width; } </script> </head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML Canvas Element width property</h2> <button onclick="getwidth ();">Get Width</button> <p id='width'></p> </center> </body> </html> |
Output:
Click the button:

When the button is clicked:

Example 2: Width attribute not provided
<!DOCTYPE html> <html> <head> <style> a:focus { background-color: magenta; } </style> <canvas id="canvas"></canvas> <script type="text/javascript"> function getwidth() { var canvas = document.getElementById('canvas'); document.getElementById('width').innerHTML = canvas.width; } </script> </head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML Canvas Element width property</h2> <button onclick="getwidth ();">Get Width</button> <p id='width'></p> </center> </body> </html> |
Output:
Click the button:

When the button is clicked:

Supported Browsers:
- Google Chrome 4
- Edge 12
- Internet Explorer 9
- Firefox 3.6
- Safari 3.1
- Opera 9
Recommended Posts:
- HTML | canvas ImageData width Property
- Web HTMLCanvasElement API | CanvasElement height property
- HTML | <canvas> width Attribute
- How to get the coordinates of a mouse click on a canvas element ?
- HTML | canvas shadowColor Property
- HTML | canvas textAlign Property
- HTML | canvas strokeStyle Property
- HTML | canvas globalAlpha Property
- HTML | canvas shadowBlur Property
- HTML | canvas fillStyle Property
- HTML | canvas shadowOffsetX Property
- HTML | canvas textBaseline Property
- HTML | canvas shadowOffsetY Property
- HTML | canvas lineCap Property
- HTML | canvas font Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai



