Is it possible to have an HTML canvas element in the background of my page?


In this article we are going to learn about is it possible to have an HTML canvas element in the background of my page.

You might try adding a CSS style with a position: fixed (or absolute, if applicable) to the canvas so that any material that comes after it will sit on top of it.

To get better understanding on is it possible to have an HTML canvas element in the background of my page, let’s look into the following examples…

Example 1

In the following example we are using the position: absolute to apply CSS style to the canvas.

<!DOCTYPE html>
<html>
   <style>
      canvas{
          position:absolute;
          left:0;
          top:0;
          z-index:-1;
          
      }
      div{
          position:absolute;
          z-index:0;
          left:11px;
          top:14px;
          
      }
   </style>
<body>
    <canvas id="mytutorial" width="450" height="500" style="border:1px solid #ABEBC6;"></canvas>
    <div>Welcome To Tutorialspoint</div>
    <script>
       var c = document.getElementById("mytutorial");
       var ctx = c.getContext("2d");
       var grd = ctx.createLinearGradient(0, 0, 600, 600);
       
       grd.addColorStop(0, "#D35400");
       grd.addColorStop(1, "#73C6B6");
       
       ctx.fillStyle = grd;
       ctx.fillRect(0, 0, 600, 600)
    </script>
</body>
</html>

On running the above script, the output window pops up, displaying the canvas as the background with the text “welcome to tutorialspoint” on the webpage.

Example 2

Let’s consider the another example for having an HTML canvas element in the background of my page.

<!DOCTYPE html>
<html>
   <style>
      body {
          background: #dddddd;
      }
      #tutorial {
          margin: 20px;
          padding: 20px;
          background: #ffffff;
          border: thin inset #aaaaaa;
          width: 600px;
          height: 300px;
      }
   </style>
<body>
    <canvas id='tutorial'></canvas>
    <script>
    var canvas = document.getElementById('tutorial'),

    context = canvas.getContext('2d');
    context.font = '38pt arial';

    context.strokeStyle = '#82E0AA';
    context.strokeText('Welcome', canvas.width/2 - 150, canvas.height/2 + 15 );
    </script>
</body>
</html>

On running the above script, it will generate an output consisting of stroke text filled on the canvas displayed on the webpage, acting as a background to the page.

Updated on: 16-Dec-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements