HTML width Attribute


The width attribute of the <canvas> element is used to set the width of the canvas in pixels. Following is the syntax −

<canvas width="pixels_val">

Above, pixels_val is the width set in pixels. Let us now see an example to implement the width attribute of the <canvas> element −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<canvas id="newCanvas" width="400" height="200" style="border:3px dashed yellow">
HTML5 canvas tag isn't supported by your browser.
</canvas>
<script>
   var c = document.getElementById("newCanvas");
   var context = c.getContext("2d");
   context.fillStyle = "#FF5655";
   context.fillRect(100, 50, 60, 100);
</script>
</body>
</html>

Output

In the above example, we have created a canvas and used JavaScript −

<script>
   var c = document.getElementById("newCanvas");
   var context = c.getContext("2d");
   context.fillStyle = "#FF5655";
   context.fillRect(100, 50, 60, 100);
</script>

Before that we have set the canvas id with width and height −

<canvas id="newCanvas" width="400" height="200" style="border:3px dashed yellow">
   HTML5 canvas tag isn't supported by your browser.
</canvas>

Updated on: 30-Jul-2019

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements