最近,一些關(guān)于HTML5愛心魚的代碼在網(wǎng)上流行。這些代碼看起來非常有趣,可以用來增加你的網(wǎng)站的趣味性。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5愛心魚代碼</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
function random(min,max) {
return Math.floor(Math.random()*(max - min)) + min;
}
function Heart(x,y,width,number,color,context) {
this.x = x;
this.y = y;
this.width = width;
this.number = number;
this.color = color;
this.context = context;
}
Heart.prototype.draw = function() {
var context = this.context;
context.save();
context.translate(this.x,this.y);
context.scale(this.width,this.width);
context.beginPath();
context.moveTo(0,0);
context.bezierCurveTo(0.25, -0.5, 0.75, -0.5, 1, 0);
context.bezierCurveTo(0.75, 0.5, 0.25, 0.5, 0, 0);
context.fillStyle = this.color;
context.fill();
context.restore();
};
Heart.prototype.update = function() {
this.x += random(-3,3);
this.y += random(-3,3);
this.width += random(-0.01,0.01);
this.width = Math.max(this.width,0.01);
this.number += 1;
this.color = 'hsl(' + this.number % 360 + ',100%,50%)';
this.draw();
};
var hearts = [];
for (var i = 0; i< 100; i++) {
hearts.push(new Heart(width/2,height/2,1,0,'hsl(' + random(0,360) + ',100%,50%)',context));
}
function render() {
context.clearRect(0,0,width,height);
for (var i = 0; i< hearts.length; i++) {
hearts[i].update();
}
requestAnimationFrame(render);
}
render();
</script>
</body>
</html>
可以看到,這段代碼使用了HTML5的canvas元素和JavaScript語言。它首先定義了一個Heart對象,該對象包含了心形的坐標(biāo)、大小、顏色和繪制函數(shù)。然后,它創(chuàng)建了100個心形對象,并通過隨機(jī)數(shù)來控制它們的移動、大小和顏色。在每個動畫幀中,代碼清除上一個幀的圖像,然后重新繪制所有心形對象。最終,這些心形對象會形成一群有趣的愛心魚,讓你的網(wǎng)站更加有趣。