Languages
[Edit]
EN

JavaScript - create layers on canvas

0 points
Created by:
Aleena
694

In this article, we would like to show you how to create layers on canvas using JavaScript.

Quick solution:

You can't create layers on a single canvas element. However, you can create multiple <canvas> elements on top of each other and achieve a similar effect.

 

Practical example

In this example, we create two functions:

  • createLayer() - creates new canvas element with the same size as the source canvas,
  • drawLayer() - draws the new layer on the top of the canvas (in 0, 0 coordinates).
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    #my-canvas { border: 1px solid gray; }

  </style>
</head>
<body>
  <canvas id="my-canvas" width="150" height="150"></canvas>
  <script>

    function createLayer(canvas) {
        var layer = document.createElement('canvas');
        layer.width = canvas.width;
        layer.height = canvas.height;
        return layer.getContext('2d');
    }
    
    function drawLayer(context, layer) {
        context.drawImage(layer.canvas, 0, 0);
    }
    
    
    // Usage example:

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');
    
    var layer1 = createLayer(canvas);
    var layer2 = createLayer(canvas);

    layer1.fillStyle = 'yellow';
    layer1.fillRect(10, 10, 100, 100);
    
    layer2.fillStyle = 'orange';
    layer2.fillRect(40, 40, 100, 100);
    
    drawLayer(context, layer1);
    drawLayer(context, layer2);

  </script>
</body>
</html>

Alternative titles

  1. JavaScript - create layers on HTML canvas element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join