Use canvas to achieve snowflake floating effect example code

Time:2021-10-15

Today we use canvas to achieve the effect of snowflakes falling ❄️

1、 What is canvas?

HTML5 < canvas > elements are used for drawing graphics and are completed by scripts (usually JavaScript)

The < canvas > tag is just a graphics container, and you must use a script to draw graphics.

You can use canvas to draw paths, boxes, circles, characters and add images in many ways.

2、 Basic usage of canvas

1. Create a canvas


<canvas id="myCanvas" width="200" height="100"></canvas>

2. Draw images using JavaScript

//First find the < canvas > element
var c=document.getElementById("myCanvas");
//Then create the context object
var ctx=c.getContext("2d");
//The following two lines of code draw a red rectangle:
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);

Getcontext (“2D”) object is a built-in HTML5 object, which has a variety of drawing paths, rectangles, circles, characters and methods to add images.

Setting the fillStyle property can be CSS color, gradient, or pattern. The default setting of fillStyle is #000000.

3. Canvas coordinates

Canvas is a two-dimensional mesh.
The coordinates of the upper left corner of the canvas are (0,0)
ctx.fillRect(0,0,150,75);
The fillRect method above has parameters (0,0150,75).
It means: draw a 150×75 rectangle on the canvas, starting from the upper left corner (0,0).

4. Canvas – path

Moveto (x, y) defines the line start coordinates
Lineto (x, y) defines the line end coordinates
To draw a circle in canvas, we will use the following method:


arc(x,y,r,start,stop)

Draw a circle using arc()


var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

3、 The idea of realizing snowflake floating

1. Create a canvas

var canvas =document.getElementById("canvas")
    //The parameter ContextID specifies the type you want to draw on the canvas.
    //Currently, the only legal value is "2D", which specifies 2D drawing,
    //And cause this method to return an environment object that exports a 2D drawing API.
    var context = canvas.getContext("2d")
    var w =window.innerWidth
    var h =window.innerHeight
    canvas.width = w;
    canvas.height =h;

2. Create an array of snowflakes

Var count = 200 // number of snowflakes
    Var snow = [] // snowflake object array
    for (var i=0 ; i< count;i++){
        snows.push({
            x: Math. Random() * W, // math. Random() is used to generate random numbers from 0 to 1
            y:Math.random()*h,
            r:Math.random()*5,
        })
    }

3. Draw snowflake style

function draw(){
        context.clearRect(0,0,w,h)
        context.beginPath()
        for(var i=0; i<count;i++){
            var snow = snows[i];// Traverse every snowflake
            Context.fillstyle = "RGB (255255255)" // set the style of snowflakes
            context.shadowBlur=10;
            context.shadowColor="rgb(255,255,255)";
            //The method of moveto is to move to the specified coordinates
            context.moveTo(snow.x,snow.y)
            //Create a circle using canvas arc()
             //x. Y, R: the X and Y coordinates of the center of the circle, and R is the radius
            //0, math. Pi * 2 start and end radians
            
            context.arc(snow.x,snow.y,snow.r,0,Math.PI * 2)
            
        }
        //Canvas fill
        context.fill()
        move()
    }

4. Realize snowflake fluttering

function move(){
        for (var i=0;i<count;i++){
            var snow =snows[i];
            Snow. Y + = (7-snow. R) / 10 // falling from top to bottom
            Snow. X + = ((5-snow. R) / 10) // falling from left to right
            if(snow.y>h){
                snows[i]={
                    x:Math.random()*w,
                    y:Math.random()*h,
                    r:Math.random()*5,
                }
            }
        }
    }

5. Set refresh

draw()
    //Refresh every millisecond
 setInterval(draw,1)

6. Complete code

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 < title > with snowflakes floating, the canvas element is used to draw graphics on Web pages</ title>
 
 <style type="text/css">
  *{
            margin:0;
            padding:0;
            /* background-color: seagreen; */
            Background: URL ("snowman. JPG") no repeat;
            background-size:100% 100%;
        }
  /* .can{
            filter: blur(1px);
        } */
 </style>
</head>
<body>
 <canvas id="canvas" class="can"></canvas>

 <script type="text/javascript">
    //The canvas element is used to draw graphics on a web page.
 var canvas =document.getElementById("canvas")
    //The parameter ContextID specifies the type you want to draw on the canvas.
    //Currently, the only legal value is "2D", which specifies 2D drawing,
    //And cause this method to return an environment object that exports a 2D drawing API.
    var context = canvas.getContext("2d")
    var w =window.innerWidth
    var h =window.innerHeight
    canvas.width = w;
    canvas.height =h;
    Var count = 200 // number of snowflakes
    Var snow = [] // snowflake object array
    for (var i=0 ; i< count;i++){
        snows.push({
            x: Math. Random() * W, // math. Random() is used to generate random numbers from 0 to 1
            y:Math.random()*h,
            r:Math.random()*5,
        })
    }
    //Draw snowflakes
    function draw(){
        context.clearRect(0,0,w,h)
        context.beginPath()
        for(var i=0; i<count;i++){
            var snow = snows[i];// Traverse every snowflake
            Context.fillstyle = "RGB (255255255)" // set the style of snowflakes
            context.shadowBlur=10;
            context.shadowColor="rgb(255,255,255)";
            //The method of moveto is to move to the specified coordinates
            context.moveTo(snow.x,snow.y)
            //Create a circle using canvas arc()
             //x. Y, R: the X and Y coordinates of the center of the circle, and R is the radius
            //0, math. Pi * 2 start and end radians
            
            context.arc(snow.x,snow.y,snow.r,0,Math.PI * 2)
           
            
        }
        //Canvas fill
        context.fill()
        move()
    }
    //Snowflakes flutter
    function move(){
        for (var i=0;i<count;i++){
            var snow =snows[i];
            Snow. Y + = (7-snow. R) / 10 // falling from top to bottom
            Snow. X + = ((5-snow. R) / 10) // falling from left to right
            if(snow.y>h){
                snows[i]={
                    x:Math.random()*w,
                    y:Math.random()*h,
                    r:Math.random()*5,
                }
            }
        }
    }
    draw()
    //Refresh every millisecond
 setInterval(draw,1)
 </script>
</body>
</html>

summary

This is the end of this article about the example code of using canvas to realize the snowflake flutter effect. For more information about snowflake flutter in canvas, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]