前端实现笛卡尔心形曲线,要求这个实现的心能跳动,直接给我代码
时间: 2024-03-15 09:43:20 浏览: 130
好的,下面是一个简单的实现,使用了 CSS3 动画和 JavaScript:
HTML 代码:
```html
<div class="heart-container">
<canvas id="heart-canvas"></canvas>
<div class="heart-heart"></div>
</div>
```
CSS 代码:
```css
.heart-container {
position: relative;
width: 200px;
height: 200px;
}
#heart-canvas {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.heart-heart {
position: absolute;
top: 90px;
left: 50px;
z-index: 2;
width: 60px;
height: 60px;
background-color: red;
transform: rotate(-45deg);
animation: heartbeat 1s ease-in-out infinite;
}
@keyframes heartbeat {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
```
JavaScript 代码:
```javascript
var canvas = document.getElementById('heart-canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var cx = w / 2;
var cy = h / 2;
var scale = 15;
function drawHeart() {
var x, y;
ctx.beginPath();
for (var t = 0; t <= Math.PI * 2; t += 0.01) {
x = scale * Math.pow(Math.sin(t), 3);
y = scale * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
ctx.lineTo(cx + x, cy - y); // 坐标系y轴向下为正,需要取负号
}
ctx.closePath();
ctx.fillStyle = 'red';
ctx.fill();
}
drawHeart();
```
效果如下所示:
![heart](https://user-images.githubusercontent.com/2215755/114659871-67e80800-9d1a-11eb-92e5-3bce4f76f2ce.gif)
阅读全文