一、前言
在浏览一些图片网站的时候,经常会看到很多的漂亮的星空图,比如,下面的图片。其实这种星星图片的效果,也可以通过html+css样式和js的方式来实现。今天教大家如何实现星星图的效果。
软件:Dreamweaver
每次刷新产生随机的星星个数。显示画布上。
<body>
<canvas id='canvas'></canvas>
</body>
给canva 画布加上边框,方便观察。
<style type="text/css">
canvas{
border:2px solid #f00;
}
</style>
<script type="text/javascript">
var _canvas=document.getElementById("canvas")
_canvas.width=500;
_canvas.height=500;
var r,g ,b,a;
</script>
for (var j = 0; j < 150; j++) {
arc.x=Math.floor(Math.random()*_canvas.width);
arc.y=Math.floor(Math.random()*_canvas.height);
arc.r=Math.floor(Math.random()*31+10);
r=Math.ceil(Math.random()*256);
g=Math.ceil(Math.random()*256);
b=Math.ceil(Math.random()*256);
a=Math.random();
darw();
}
如何画星星?(公式解析)(图片来源百度)
星星有内切圆和外切圆,每两个点之间的角度是固定的,因此可得到星星的每个点的坐标,画出星星。
/* 随机产生星星*/
for (var i = 0; i < 5; i++) {
_ctx.lineTo(Math.cos((18+72*i)/180*Math.PI)*arc.r+arc.x, -Math.sin((18+72*i)/180*Math.PI)*arc.r+arc.y);
_ctx.lineTo(Math.cos((54+72*i)/180*Math.PI)*arc.r/2+arc.x, -Math.sin((54+72*i)/180*Math.PI)*arc.r/2+arc.y);
}
Math函数随机产生0-225的RGB值。
/* 随机颜色*/
_ctx.fillStyle="rgba(" + r + "," + g + "," + b + "," + a + ")";
_ctx.fill();
_ctx.strokeStyle="rgba(" + r + "," + g + "," + b + "," + a + ")";
_ctx.stroke();
}
darw();
1、点击f12运行到浏览器
2、每次刷新网页,随机产生不一样的星星和随机颜色。
------------------- End -------------------