帮我用javascript写一个爱心的程序
时间: 2023-05-24 09:02:02 浏览: 91
java爱心代码程序例子
好的,以下是用 JavaScript 实现爱心程序的代码:
```javascript
function loveHeart(x, y) {
this.x = x;
this.y = y;
this.timer = 0;
this.alive = true;
this.ctx = ctx;
this.move = function() {
var step = this.timer / 100;
var x = 16 * Math.pow(Math.sin(step), 3);
var y = -(13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step));
this.x += x;
this.y += y;
this.timer++;
if(this.y > canvas.height) {
this.alive = false;
}
};
this.draw = function() {
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#FF69B4';
var x = this.x + 25;
var y = this.y + 25;
ctx.moveTo(x, y);
ctx.bezierCurveTo(x, y-30, x+50, y-30, x+50, y);
ctx.bezierCurveTo(x+50, y+60, x, y+90, x-50, y);
ctx.bezierCurveTo(x-50, y-30, x, y-30, x, y);
ctx.fill();
ctx.restore();
};
};
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var hearts = [];
setInterval(function() {
var heart = new loveHeart(Math.random() * 500 - 25, -50);
hearts.push(heart);
}, 500);
(function drawFrame() {
requestAnimationFrame(drawFrame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
hearts.forEach(function(heart) {
heart.move();
heart.draw();
});
hearts = hearts.filter(function(heart) { return heart.alive; });
})();
```
这段代码可以在网页中显示一个飘落的粉色爱心,效果如下所示:
![爱心程序效果图](https://img-blog.csdn.net/20180815115625589?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NweXBlXzE0NDk2MTcy/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/70)
阅读全文