HTML5 > Canvas Animation

Layering on Canvas in HTML5

How to create the layers on the canvas?


Canvas Layers 

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>
  • In the above code snippet we have defined the layers in the canvas
  • We have created the canvas element id as mycanvas and width value 250, height value 200
  • In the script function we are calling the window.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
  • In the nextline we are having the function as drawlayer1 and drawlayer2, we have defined the values of the fillstyle and fillRect values of the layers
  • function draw is used to call the clearRect with the (x, y, width, height) values
  • In the nextline we are checking the if 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



Write for us






Hosting Recommendations