EN
JavaScript - create layers on canvas
0
points
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 newcanvas
element with the same size as the sourcecanvas
,- 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>