用文本写一个html的樱花树
时间: 2023-10-05 13:11:12 浏览: 86
HTML5 Canvas樱花树木特效.zip
<!DOCTYPE html>
<html>
<head>
<title>樱花树</title>
<style>
body {
background-color: #fafafa;
}
canvas {
position: absolute;
}
</style>
</head>
<body>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
var petals = [];
var numPetals = 200;
var speed = 1;
var wind = 0;
var gravity = 0.05;
var bloom = false;
var centerX = width / 2;
var centerY = height - 100;
var radius = 50;
var petalImg = new Image();
petalImg.src = 'https://raw.githubusercontent.com/hannahwu1994/sakura/master/img/petal.png';
function init() {
for (var i = 0; i < numPetals; i++) {
var angle = Math.random() * Math.PI * 2;
var distance = Math.random() * radius;
var x = centerX + distance * Math.cos(angle);
var y = centerY - distance * Math.sin(angle);
var petal = {};
petal.x = x;
petal.y = y;
petal.velX = 0;
petal.velY = 0;
petal.angle = 0;
petals.push(petal);
}
}
function update() {
for (var i = 0; i < numPetals; i++) {
var petal = petals[i];
if (!bloom) {
var distance = Math.sqrt(Math.pow(petal.x - centerX, 2) + Math.pow(petal.y - centerY, 2));
if (distance < radius) {
petal.velX = 0;
petal.velY = 0;
petal.angle = Math.atan2(petal.y - centerY, petal.x - centerX);
bloom = true;
} else {
petal.angle += Math.random() * 0.1 - 0.05 + wind;
petal.velX = Math.cos(petal.angle);
petal.velY = -Math.sin(petal.angle);
}
} else {
petal.velY += gravity;
petal.y += petal.velY * speed;
petal.x += petal.velX * speed;
}
}
}
function draw() {
context.clearRect(0, 0, width, height);
for (var i = 0; i < numPetals; i++) {
var petal = petals[i];
context.save();
context.translate(petal.x, petal.y);
context.rotate(Math.atan2(petal.velY, petal.velX));
context.drawImage(petalImg, -petalImg.width/2, -petalImg.height/2);
context.restore();
}
}
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
init();
loop();
</script>
</body>
</html>
阅读全文