java script 爱心代码高级
时间: 2025-05-05 20:21:00 浏览: 23
JavaScript 实现爱心效果是一种非常有趣的方式,可以用于网站装饰、动画展示等场景。下面将向您介绍一种基于Canvas绘图的高级 JavaScript 爱心代码。
要创建这样一个动态的心形图案,首先需要了解 HTML5 中 Canvas 元素的基本知识以及如何通过 JavaScript 对其进行操作。接下来我们来看一段具体的示例代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Heart Animation</title>
<style>
body { background-color:#000; }
canvas{ display:block;margin:auto;}
</style>
</head>
<body>
<canvas id="heart" width="600" height="400"></canvas>
<script type="text/javascript">
const canvas = document.getElementById('heart');
const ctx = canvas.getContext('2d');
// 设置画布大小自适应窗口变化
window.onresize = resizeCanvas;
function resizeCanvas() {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
draw();
}
resizeCanvas();
let t = 0;
function draw(){
// 清除屏幕内容并设置背景颜色
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制心型曲线公式,并填充渐变色
const heartPath = (t) => ({
x: 16 * Math.pow(Math.sin(t), 3),
y: -(13*Math.cos(t)-5*Math.cos(2*t)-2*Math.cos(3*t)-Math.cos(4*t))
});
for(let i=0;i<=70;++i){
let angle = -Math.PI + i*(Math.PI*2/70);
var gradient = ctx.createRadialGradient(
canvas.width / 2 + heartPath(angle).x * 9,
canvas.height / 2 + heartPath(angle).y * 9,
0,
canvas.width / 2 + heartPath(angle).x * 9,
canvas.height / 2 + heartPath(angle).y * 9,
30-i
)
gradient.addColorStop(0,"rgba("+[255*i/70|0,51,153].join(",")+",.9)");
gradient.addColorStop(.8,"#"+("ffccf"+"f").slice(i%12&1?3:0));
gradient.addColorStop(1,"transparent");
ctx.beginPath();
ctx.arc(canvas.width / 2 + heartPath(angle).x * 9 , canvas.height / 2+ heartPath(angle).y * 9,i*.5,0,Math.PI * 2, false);
ctx.fillStyle = gradient;
ctx.fill();
}
t+= .0005;
if (t > Math.PI * 2) t -= Math.PI * 2;
requestAnimationFrame(draw);
}
draw()
</script>
</body>
</html>
```
上述代码中,`heartPath()` 函数定义了心形路径方程;然后利用 `for循环` 和 `createRadialGradient()` 方法生成一系列从中心向外扩散的颜色过渡圆环来构建出整个图形的效果。最后借助于 `requestAnimationFrame()` 进行帧渲染更新,实现了平滑流畅地动画呈现。
您可以尝试调整一些参数如圆形半径、梯度色彩范围值等来自定义这个心形特效!
阅读全文
相关推荐










