Use canvas to achieve the effect of snowflakes floating


Preface

Layers of pine branches on the surrounding mountains, wearing white velvet-like thick snow, sinking and drooping, from time to time fell two palm-sized pieces of snow, silently piled on the snow-Bing Xin "Send to Little Readers"

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


1. What is canvas?

HTML5 <canvas>elements are used to draw graphics and are done through scripts (usually JavaScript).

<canvas> The label is just a graphic container, you must use a script to draw the graphic.

You can use a variety of ways canvasto draw paths, boxes, circles, characters, and adding images.

Two, the basic usage of canvas

1. Create a canvas (Canvas)

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

2. Use JavaScript to draw images

//首先找到<canvas>元素
var c=document.getElementById("myCanvas");
//然后创建context对象
var ctx=c.getContext("2d");
//下面的两行代码绘制一个红色的矩形:
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);

getContext("2d")The object is a built-in HTML5 object with multiple methods for drawing paths, rectangles, circles, characters, and adding images .

Setting fillStyleattributes can be CSS colors, gradients, or patterns. fillStyleThe default setting is #000000.


3.Canvas coordinates

canvasIt is a two-dimensional grid.
canvasThe upper-left corner coordinates (0,0)
ctx.fillRect(0,0,150,75);
The above fillRectmethod has a parameter (0,0,150,75).
Meaning: draw a 150x75 rectangle on the canvas, starting from the upper left corner (0,0).

4.Canvas-Path

moveTo(x,y)Define the start coordinates of the
lineTo(x,y)line Define the end coordinates of the line To
draw a circle on the canvas, we will use the following methods:

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

Use to arc()draw a circle

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

Third, the idea of ​​realizing snowflakes fluttering

1. Create a canvas (Canvas)

	var canvas =document.getElementById("canvas")
    //参数 contextID 指定了您想要在画布上绘制的类型。
    //当前唯一的合法值是 "2d",它指定了二维绘图,
    //并且导致这个方法返回一个环境对象,该对象导出一个二维绘图 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 //雪花的个数
    var snows=[] //雪花对象数组
    for (var i=0 ; i< count;i++){
    
    
        snows.push({
    
    
            x:Math.random()*w,//Math.random()用于生成0~1的随机数
            y:Math.random()*h,
            r:Math.random()*5,
        })
    }

3. Draw the snowflake style

	function draw(){
    
    
        context.clearRect(0,0,w,h)
        context.beginPath()
        for(var i=0; i<count;i++){
    
    
            var snow = snows[i];//遍历每一片雪花
            context.fillStyle ="rgb(255,255,255)" //设置雪花的样式
            context.shadowBlur=10;
            context.shadowColor="rgb(255,255,255)";
            //moveTo 的方法是可以移动到指定的坐标
            context.moveTo(snow.x,snow.y)
            // 使用canvas arc()创建一个圆形
             //x,y,r:圆的中心的x坐标和y坐标,r为半径
            //0,Math.PI * 2起始弧度和结束弧度
            
            context.arc(snow.x,snow.y,snow.r,0,Math.PI * 2)
            
        }
        //画布填充
        context.fill()
        move()
    }

4. Realize the snow flutter

	function move(){
    
    
        for (var i=0;i<count;i++){
    
    
            var snow =snows[i];
            snow.y +=(7-snow.r)/10 //从上往下飘落
            snow.x+=((5-snow.r)/10)//从左到右飘落
            if(snow.y>h){
    
    
                snows[i]={
    
    
                    x:Math.random()*w,
                    y:Math.random()*h,
                    r:Math.random()*5,
                }
            }
        }
    }

5. Set refresh

 	draw()
    //每毫秒刷新一次
	setInterval(draw,1)

6. Complete code

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>雪花飘飘之使用canvas元素用于在网页上绘制图形。</title>
 
	<style type="text/css">
		*{
     
     
            margin:0;
            padding:0;
            /* background-color: seagreen; */
            background: url("雪人.jpg")  no-repeat;
            background-size:100% 100%;
        }
		/* .can{
            filter: blur(1px);
        } */
	</style>
</head>
<body>
	<canvas id="canvas" class="can"></canvas>

	<script type="text/javascript">
    //canvas 元素用于在网页上绘制图形。
	var canvas =document.getElementById("canvas")
    //参数 contextID 指定了您想要在画布上绘制的类型。
    //当前唯一的合法值是 "2d",它指定了二维绘图,
    //并且导致这个方法返回一个环境对象,该对象导出一个二维绘图 API。
    var context = canvas.getContext("2d")
    var w =window.innerWidth
    var h =window.innerHeight
    canvas.width = w;
    canvas.height =h;
    var count =200 //雪花的个数
    var snows=[] //雪花对象数组
    for (var i=0 ; i< count;i++){
     
     
        snows.push({
     
     
            x:Math.random()*w,//Math.random()用于生成0~1的随机数
            y:Math.random()*h,
            r:Math.random()*5,
        })
    }
    //绘制雪花
    function draw(){
     
     
        context.clearRect(0,0,w,h)
        context.beginPath()
        for(var i=0; i<count;i++){
     
     
            var snow = snows[i];//遍历每一片雪花
            context.fillStyle ="rgb(255,255,255)" //设置雪花的样式
            context.shadowBlur=10;
            context.shadowColor="rgb(255,255,255)";
            //moveTo 的方法是可以移动到指定的坐标
            context.moveTo(snow.x,snow.y)
            // 使用canvas arc()创建一个圆形
             //x,y,r:圆的中心的x坐标和y坐标,r为半径
            //0,Math.PI * 2起始弧度和结束弧度
            
            context.arc(snow.x,snow.y,snow.r,0,Math.PI * 2)
           
            
        }
        //画布填充
        context.fill()
        move()
    }
    //雪花飘动
    function move(){
     
     
        for (var i=0;i<count;i++){
     
     
            var snow =snows[i];
            snow.y +=(7-snow.r)/10 //从上往下飘落
            snow.x+=((5-snow.r)/10)//从左到右飘落
            if(snow.y>h){
     
     
                snows[i]={
     
     
                    x:Math.random()*w,
                    y:Math.random()*h,
                    r:Math.random()*5,
                }
            }
        }
    }
    draw()
    //每毫秒刷新一次
	setInterval(draw,1)
	</script>
</body>
</html>

Insert picture description here

to sum up

The above is the content to be talked about today. This article briefly introduces the use of canvas and the steps of how to achieve the effect of falling snow~

Guess you like

Origin blog.csdn.net/weixin_43633329/article/details/114915047