It is used to create the different layers in the canvas element
<h2 style=" color:magenta"><i>canvas layers</i></h2> <canvas id="mycanvas" width="250" height="200" style="border:5px solid green"></canvas> <script> window.addEventListener('load', function () { var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); var order = 0; function drawLayer1() { ctx.fillStyle = "rgb(20,0,10)"; ctx.fillRect(20, 20, 75, 80); } function drawLayer2() { ctx.fillStyle = "rgba(10, 20,900, 9.5)"; ctx.fillRect(30, 30, 50, 50); } function draw() { ctx.clearRect(0, 0, 250, 150); if (order === 0) { drawLayer1(); drawLayer2(); } else { drawLayer2(); drawLayer1(); } } setInterval(draw, 100); setInterval(function () { order = 1 - order; }, 200); }, false); </script>
layers
in the canvasmycanvas
and width value 250, height value 200window.addeventlistener
as the function load, we have given the var canvas id
as mycanvas
and context as canvas
var order =0
- It defines the order as 0 drawlayer1
and drawlayer2
, we have defined the values of the fillstyle
and fillRect
values of the layersclearRect
with the (x, y, width, height)
valuesif
condition with the with the order as 0 drawlayer1
and drawlayer2
, else drawlayer2 and drawlayer1
setInterval(draw, 100);
- It animates the function drawlayer with the value 100
setIntervalfunction () -
The setinterval function calls the draw function to animate the layers
output
Views: 9160 | Post Order: 111