SVG彩虹字

时间:2022-08-19 15:11:10

SVG彩虹字


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="900px">
<defs>
<pattern id="grid" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<path stroke="#f0f0f0" fill="none" d="M0,0H20V20"></path>
</pattern>
</defs>
<rect width="1200" height="1000" fill="url(#grid)"></rect>
<text id="sintext" x="100" y="160" style="font-size: 14px;font-family:'Arial'"></text>
</svg>
<script>
var NS = 'http://www.w3.org/2000/svg';
var text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var n = text.length;
var x = [];
var y = null;
var i = n;
var s = 100;
var w = 0.02;
var t = 0; while(i--) {
x.push(10);
var tspan = document.createElementNS(NS,'tspan');
tspan.textContent = text[n - i - 1];
sintext.appendChild(tspan);
var h = Math.round(360/26*i); //色环360度放到26个字母上,i当前字母
tspan.setAttribute('fill','hsl('+h+',100%,80%)');
};
function arrange(t){
y = [];
var ly = 0,cy;
for (i=0;i<n;++i){
cy = -s * Math.sin(w * i * 20 + t);
y.push(cy-ly);
ly = cy;
}
console.table(y);
}
function render(){
sintext.setAttribute('dx', x.join(' '));
sintext.setAttribute('dy', y.join(' '));
}
function frame(){
t += 0.01;
arrange(t);
render();
requestAnimationFrame(frame);
}
frame();
</script>
</body>
</html>