SVG绘制星空
程序员文章站
2022-05-27 08:32:43
...
利用SVG绘制一片星空
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SVG星空</title>
<style type="text/css">
*{padding: 0;margin: 0;}
html,body{
width: 100%;
height: 100%;
background: #001122;
}
</style>
<script type="text/javascript">
window.onload = function(){
var NS = "http://www.w3.org/2000/svg";
var svg = document.getElementById("svg");
var group = document.getElementById("star-group");
var count = 500; //星星数量
var svg_width = parseFloat(getComputedStyle(svg).width);
var svg_height = parseFloat(getComputedStyle(svg).height);
//生成min-max的随机数
function random(min,max){
return Math.random()*(max-min)+min;
}
while(count--){
var use = document.createElementNS(NS,"use");
use.setAttribute("href","#star");
//随机设置星星的位置与大小
use.setAttribute("transform","translate("+random(0,svg_width-20)+","+random(0,svg_height-20)+")"+"scale("+random(0.1,0.6)+")");
//随机设置星星的透明度
use.setAttribute("opacity",random(0,1).toString());
group.appendChild(use);
}
}
</script>
</head>
<body>
<svg id="svg" width="100%" height="100%">
<defs>
<polygon id="star" points="10 0 12 8 20 10 12 12 10 20 8 12 0 10 8 8" fill="white"></polygon>
</defs>
<g id="star-group"></g>
</svg>
</body>
</html>