<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
:root,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
/*@type:HTMLCanvasElement*/
const canvas = document.getElementById('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
const ctx = canvas.getContext('2d')
ctx.beginPath()
// 绘制线
function show() {
ctx.save()
ctx.translate(100, 100)
ctx.lineCap = 'round'
ctx.lineWidth = 5
ctx.strokeStyle = "white"
// 第一根线
ctx.moveTo(-20, 0)
ctx.lineTo(20, 0)
/*
sin60 = 对边/斜边 => 对边 = sin60*斜边 => y = sin60%半径
sin30 = 对边/斜边 => 对边 = sin30*斜边 => x = sin30%半径
*/
var disY = Math.sin(60 * Math.PI / 180) * 20
var disX = Math.sin(30 * Math.PI / 180) * 20
// 第二根线
ctx.moveTo(-disX, -disY)
ctx.lineTo(disX, disY)
// 第三根线
ctx.moveTo(-disX, disY)
ctx.lineTo(disX, -disY)
ctx.stroke()
ctx.restore()
}
// show()
function Snow(x, y, scale, rotate, speedX, speedY, speedR) {
this.x = x;
this.y = y;
this.scale = scale;
this.rotate = rotate;
this.speedX = speedX;
this.speedY = speedY;
this.speedR = speedR;
}
Snow.prototype.render = function () {
ctx.beginPath()
ctx.save()
ctx.translate(this.x, this.y)
ctx.scale(this.scale, this.scale)
ctx.rotate(this.rotate * Math.PI / 180)
ctx.lineCap = 'round'
ctx.lineWidth = 5
ctx.strokeStyle = "white"
// 第一根线
ctx.moveTo(-20, 0)
ctx.lineTo(20, 0)
var disY = Math.sin(60 * Math.PI / 180) * 20
var disX = Math.sin(30 * Math.PI / 180) * 20
// 第二根线
ctx.moveTo(-disX, -disY)
ctx.lineTo(disX, disY)
// 第三根线
ctx.moveTo(-disX, disY)
ctx.lineTo(disX, -disY)
ctx.stroke()
ctx.restore()
}
// var snow = new Snow(100, 100, 1, 10, 10, 10, 10)
// snow.render()
const sonwArr = []
init()
function init() {
let len = 100
for (var i = 0; i < len; i++) {
let x = Math.random() * canvas.width;
let scale = Math.random() + 0.5;
let rotate = Math.random() * 60;
let speedX = Math.random() + 1;
let speedY = Math.random() + 5;
let speedR = Math.random() * 4 + 2; // 旋转速度
// console.log(x, 0, scale, rotate, speedX, speedY, speedR)
( function(x, y, scale, rotate, speedX, speedY, speedR){
setTimeout(function () {
let snow = new Snow(x, y, scale, rotate, speedX, speedY, speedR)
snow.render()
sonwArr.push(snow)
}, Math.random() * 8000)
}(x, 0, scale, rotate, speedX, speedY, speedR))
}
snowing()
}
function snowing() {
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
for (var i = 0; i < sonwArr.length; i++) {
sonwArr[i].x = (sonwArr[i].x + sonwArr[i].speedX) % canvas.width
sonwArr[i].y = (sonwArr[i].y + sonwArr[i].speedY) % canvas.height
sonwArr[i].rotate = (sonwArr[i].rotate + sonwArr[i].rotate ) % 30
sonwArr[i].render()
}
}, 30);
}
</script>
</body>
</html>
canvas 雪花
最新推荐文章于 2022-11-05 22:00:11 发布
此博客围绕Canvas绘制雪花展开。Canvas是前端开发中用于图形绘制的重要工具,通过它可实现雪花的绘制效果,在前端页面中增添生动元素,为用户带来更好的视觉体验。
6962

被折叠的 条评论
为什么被折叠?



