用js画一个会动的爱心
时间: 2024-06-08 16:07:07 浏览: 6
好的,以下是一个简单的用 JavaScript 画动态爱心的代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态爱心</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
function render() {
ctx.clearRect(0, 0, width, height);
var time = Date.now() * 0.001;
var x = width * 0.5 + Math.sin(time) * width * 0.2;
var y = height * 0.5 + Math.cos(time * 0.9) * height * 0.3;
var size = Math.abs(Math.sin(time * 1.2)) * 50 + 50;
drawHeart(x, y, size);
requestAnimationFrame(render);
}
function drawHeart(x, y, size) {
ctx.beginPath();
ctx.moveTo(x, y - size * 0.5);
ctx.bezierCurveTo(x + size * 0.6, y - size * 0.8, x + size * 0.9, y, x, y + size * 0.8);
ctx.bezierCurveTo(x - size * 0.9, y, x - size * 0.6, y - size * 0.8, x, y - size * 0.5);
ctx.fillStyle = 'red';
ctx.fill();
}
render();
</script>
</body>
</html>
```
这个代码会在页面上画一个动态的爱心,位置和大小会随着时间变化而变化。可以在浏览器中打开这个代码,看看效果。