当我们想自己制作属于自己的网页背景动态图的时候,又不想去网上搜用别人的素材,那么这个时候你的技术就排上用场了,canvas可以制作一个很好看的动态背景图喔!
本次用到的技术点有canvas的基本使用,JavaScript面向对象
先看效果图吧:
我的雪花半径设置得有点小,后期半径可自己设置
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>雪花起始页</title>
<link rel="stylesheet" href="./css/起始页.css">
<script src="./js/起始页.js"></script>
</head>
<body>
<canvas id="can"></canvas>
<div id="cen">M6 Q9</div>
</body>
</html>
html部分只需要一个canvas画布即可,后期动画效果需要用到JavaScript渲染
css部分:
@charset 'utf-8';
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
height: 100vh;
background:url(../img/天空\ 云\ 阳光\ 黑暗\ 4K风景壁纸_彼岸图网.jpg) center / cover;
display: flex;
justify-content: center;
align-items: center;
}
#can{
position: absolute;
z-index: -1;
filter: blur(0.8px);
}
#cen{
width: 320px;
height: 320px;
border-radius: 50%;
border: rgb(233, 227, 227) solid 1px;
box-shadow: inset 0px 0px 18px rgb(226, 223, 223);
text-align: center;
line-height: 320px;
font-size: 26px;
color: white;
}
重点,JavaScript部分,这里利用了 ES6语法糖,将每一个雪花封装到一个对象中
window.onload = function () {
/**@type{HTMLCanvasElement}*/
var can = document.getElementById("can")
can.width = window.innerWidth
can.height = window.innerHeight
let ctx = can.getContext("2d")
let arr = []
//雪花类
class XX {
constructor() {
this.r = this.cs().r;
this.x = this.cs().x;
this.y = this.cs().y;
this.vy = this.cs().vy;
this.vx = this.cs().vx;
this.color = 'rgb(255,255,255)'
this.show = this.r * 2
arr.push(this)
}
//随机参数
cs() {
return {
x: parseInt(Math.random() * can.width),
y: parseInt(Math.random() * can.height),
r: (Math.random() * 2).toFixed(3),
vx: 0.5 - Math.random() * 1,
vy: 2.5 - this.r
}
}
//生成小雪花
xxx() {
ctx.beginPath()
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI)
ctx.fillStyle = this.color
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 0
ctx.shadowColor = this.color
ctx.shadowBlur = 20
ctx.fill()
ctx.closePath()
// console.log(1);
// for(let i=0;i<arr.length;i++){
// if(Math.abs(arr[i].x-this.x)<100 && Math.abs(arr[i].y-this.y)<100){
// ctx.strokeStyle = "orange"
// ctx.beginPath()
// //小球线的透明度
// ctx.globalAlpha = 10/Math.sqrt(Math.pow(arr[i].x - this.x,2)+Math.pow(arr[i].y-this.y,2) )
// ctx.moveTo(this.x,this.y)
// ctx.lineTo(arr[i].x,arr[i].y)
// ctx.closePath()
// ctx.stroke()
// console.log(this.x,this.y);
// }
// }
}
//星星移动
move() {
this.y += this.vy
this.x += this.vx
if (this.x < 0) {
this.x = this.cs().x
}
if (this.x > can.width) {
this.x = this.cs().x
}
if (this.y > can.height) {
this.y = 0
}
}
};
//实例化类
function sl(z) {
for (let i = 0; i <= z; i++) {
new XX()
arr[i].xxx()
}
console.log(arr);
}
sl(300)
function movew() {
setInterval(function () {
ctx.clearRect(0, 0, can.width, can.height)
for (let i = 0; i < arr.length; i++) {
arr[i].move()
arr[i].xxx()
}
}, 1000/60)
}
movew()
};
在class中,我们可以将每个实例出的对象装到数组中,达到后期运动对每一片雪花的批量操作,
这个效果的知识点涉及到JavaScript面向对象,编程思维是将每一片雪花相同的功能封装起来,再去实例化调用
本次分享就到这里了,本人是个三观超正的博主 ,期待你的关注!!!