HTML Canvas - Width Property



The HTML Canvas width property of HTMLCanvasElement interface accepts a positive integer and then sets the width size of the Canvas element layout.

It is passed as an attribute to the Canvas tag in HTML5 code. When the property is not given, the default value of 300 is used. It basically controls the width of Canvas element.

Possible input values

It accepts all positive integer values and applies the value to width of the Canvas element in pixels.

Example

The following example uses default HTML Canvas width property value and constructs the Canvas element layout.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" style="border: 1px solid black;"></canvas>
   </body>
</html>

Output

Since we did not give the value of width in the above code, the default value of Canvas width is considered (300) and the Canvas element layout is drawn. The output given by the above code on the webpage as −

Html Canvas Width Property

Example

The following example demonstrates how width property of the Canvas element can be used to change dimensions of the Canvas.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas1" width="100" style="border: 1px solid rgb(100, 82, 117);"></canvas>
      <canvas id="canvas2" width="200" style="border: 1px solid rgb(43, 236, 43);"></canvas>
   </body>
</html>

Output

The program creates two canvases with different widths and shows how the property can change the layout of Canvas element. The above code returns the output on a new webpage as −

Html Canvas Width Property

Example

The following example displays the width of the Canvas element in console as well as the window alert.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="Context();">
      <canvas id="canvas" width="600" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         console.log('Canvas width : ' + canvas.width);
         window.alert('canvas width is ' + canvas.width);
      </script>
</html>

Output

The program creates a canvas with input width and shows it on console and window alert. The above code returns the output by window alert as −

Html Canvas Width Property

The output shown in console as −

Html Canvas Width Property

The canvas formed by the above code on the webpage as −

Html Canvas Width Property
html_canvas_element.htm
Advertisements