One, foreword
When browsing some image websites, you will often see a lot of beautiful sky maps, such as the picture below. In fact, this kind of star image effect, can also be achieved through HTML + CSS style and JS. Today I’m going to teach you how to achieve the effect of the star map.
Ii. Project preparation
Software: Dreamweaver
Iii. Goals achieved
Each refresh produces a random number of stars. Display on canvas.
Iv. Project realization
1. Create a Canvas canvas
<body>
<canvas id='canvas'></canvas>
</body>
Copy the code
2. Add CSS styles.
Border the Canva canvas for easy viewing.
<style type="text/css">
canvas{
border:2px solid #f00;
}
</style>
Copy the code
3. Add JS styles
3.1 Setting the canvas Canvas size and defining required variables.
<script type="text/javascript">
var _canvas=document.getElementById("canvas")
_canvas.width=500;
_canvas.height=500;
var r,g ,b,a;
</script>
Copy the code
3.2 Generating random circles.
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();
}
Copy the code
3.3 Define draw() method, by drawing the star formula, convert the circle into a star for loop to generate random position stars.
How to draw stars? (Formula analysis) (Photo courtesy Baidu)
Stars have tangential circles and tangential circles, and the angles between each two points are fixed, so the coordinates of each point of the star can be obtained, and the stars can be drawn.
/* 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); }Copy the code
3.4 Random color generation.
The Math function randomly generates RGB values from 0 to 225.
/ * * / _ctx. Random color fillStyle = "rgba (" + r +", "+ g +", "a + b +", "+ a +") "; _ctx.fill(); _ctx.strokeStyle="rgba(" + r + "," + g + "," + b + "," + a + ")"; _ctx.stroke(); }Copy the code
3.5. Call the draw() method to implement the function.
darw();
Copy the code
5. Effect display
1. Click F12 to open the browser
2, every time you refresh the page, randomly generate different stars and random colors.
Six, summarized
- This project uses canvas canvas to achieve the effect of star map, and analyzes some difficulties encountered when using javascript to produce the star effect and provides solutions.
- Welcome to actively try, sometimes see others to achieve it is very simple, but when it comes to their own hands, there will always be a variety of problems, do not be arrogant, often start, can understand more profound.
- The code is very simple and hopefully enlightening to you.
Learn more about front-end, Python crawlers, big data and more at pdcfighting.com/