在HTML中,创建一个跳动的爱心可以使用HTML5的<canvas>
元素和JavaScript。以下是一个简单的示例,展示了如何创建两个同时跳动的爱心:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
background-color: #f3f3f3;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="heart1" width="200" height="200"></canvas>
<canvas id="heart2" width="200" height="200"></canvas>
<script>
function drawHeart(id, x, y, scale) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
var radius = 10;
var xScale = x;
var yScale = y;
var scaleFactor = scale;
ctx.save();
ctx.scale(scaleFactor, scaleFactor);
ctx.beginPath();
ctx.translate(xScale, yScale);
ctx.moveTo(0, radius);
ctx.quadraticCurveTo(radius, radius, radius, 0);
ctx.quadraticCurveTo(2 * radius, 0, 3 * radius, radius);
ctx.quadraticCurveTo(4 * radius, radius, 3 * radius, 2 * radius);
ctx.quadraticCurveTo(4 * radius, 2 * radius, 3 * radius, 3 * radius);
ctx.quadraticCurveTo(2 * radius, 3 * radius, radius, 3 * radius);
ctx.quadraticCurveTo(radius, 2 * radius, 0, 2 * radius);
ctx.quadraticCurveTo(-radius, 2 * radius, -radius, radius);
ctx.quadraticCurveTo(-2 * radius, radius, -3 * radius, 0);
ctx.quadraticCurveTo(-4 * radius, 0, -3 * radius, -radius);
ctx.quadraticCurveTo(-2 * radius, -radius, -radius, -2 * radius);
ctx.quadraticCurveTo(0, -2 * radius, radius, -2 * radius);
ctx.closePath();
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
}
function animateHeart(id, x, y, scale) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
var scaleFactor = scale;
var xScale = x;
var yScale = y;
var frame = 0;
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawHeart(id, xScale + 90 * Math.sin(frame * 0.1), yScale + 30 * Math.cos(frame * 0.1), scaleFactor);
frame++;
}, 100);
}
drawHeart('heart1', 60, 60, 1);
drawHeart('heart2', 120, 60, 1);
animateHeart('heart1', 60, 60, 1);
animateHeart('heart2', 120, 60, 1);
</script>
</body>
</html>
这段代码定义了一个drawHeart
函数来绘制心形,以及一个animateHeart
函数来动画化心形的跳动。两个心形会在页面中跳动。这里使用了<canvas>
元素来绘图,并通过JavaScript来控制动画。通过调整x
, y
, 和 scale
参数,可以控制心形的位置和大小。