用Javascript写一个动态爱心
时间: 2024-06-12 18:04:24 浏览: 151
很好,这是一个有趣的问题!以下是一个简单的示例代码,可以在HTML页面中使用:
```html
<!DOCTYPE html>
<html>
<head>
<title>动态爱心</title>
<style>
body {
background-color: #f5f5f5;
text-align: center;
font-family: Arial, sans-serif;
}
canvas {
border: 1px solid #ccc;
margin-top: 50px;
}
</style>
</head>
<body>
<h1>动态爱心</h1>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// 设置颜色和样式
context.fillStyle = '#ff0000';
context.strokeStyle = '#000000';
context.lineWidth = 2;
// 绘制爱心
var x = canvas.width / 2;
var y = canvas.height / 2;
var size = 100;
var angle = 0;
var speed = 0.01;
function drawHeart() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(x, y - size / 4);
context.quadraticCurveTo(x - size / 2, y - size / 2, x, y + size / 2);
context.quadraticCurveTo(x + size / 2, y - size / 2, x, y - size / 4);
context.closePath();
context.fill();
context.stroke();
angle += speed;
x = canvas.width / 2 + size * Math.sin(angle);
y = canvas.height / 2 + size * Math.cos(angle);
requestAnimationFrame(drawHeart);
}
drawHeart();
</script>
</body>
</html>
```
该代码会在画布上绘制一个红色的爱心,然后让它动起来。具体来说,它每帧都会重新绘制爱心,但这次会沿着一个正弦曲线移动。这样就会让爱心在画布上来回摆动,非常有趣!
阅读全文