绘制满天星我们需要黑色的天空,若干星星散落在天空各个地方
1、夜晚的天空,全屏黑色
2.在画布上画星星,也就是画布也应该是全屏
var ctx = document.getElementById('canvas')
context = ctx.getContext('2d')
HEIGHT = document.documentElement.clientHeight
WIDTH = document.documentElement.clientWidth
ctx.width = WIDTH
ctx.height = HEIGHT
3.创建一个星星的类,星星的位置,透明度,半径,颜色随机,为了区分不同的星星要有一个id或者唯一的数据标识
function Start_item (index, x, y) {
this.index = index //唯一标识
this.x = x //横坐标
this.y = y //纵坐标
this.r = Math.random()*2 + 1 //1——3的半径,这个自由发挥
this.alpha = (Math.floor(Math.random()*10 + 1))/2/10 //0.1——0.55的透明度
this.color = "rgba(255, 255, 255, "+ this.alpha +")"
}
4.知道星星的基本条件需要把星星给画出来
Start_item.prototype.draw = function () {
context.fillStyle = this.color
context.shadowBlur = this.r*3
context.beginPath()
context.arc(this.x, this.y, this.r, 2*Math.PI, false)
context.closePath()
context.fill()
}
5.需要花很多星星,这个可以自由规范,我就花天上花130颗星星,所有的星星用一个数组装起来
由于每个星星都应该在画布上,所以最大横纵坐标就是屏幕的宽高,Math.random()的范围是0—1,故以下计算坐标
function init () {
for (let i = 0; i < startNum; i ++) {
startArr[i] = new Start_item(i, Math.random()*WIDTH, Math.random()*HEIGHT)
startArr[i].draw()
}
}
6.最后一步走起来
init()
这样漫天星星久画出来了
以下是完整代码:(本人也是canvas初学者,有问题就指出来哈)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background: black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var ctx = document.getElementById('canvas')
context = ctx.getContext('2d')
HEIGHT = document.documentElement.clientHeight
WIDTH = document.documentElement.clientWidth
startNum = 130
startArr = []
ctx.width = WIDTH
ctx.height = HEIGHT
function Start_item (index, x, y) {
this.index = index
this.x = x
this.y = y
this.r = Math.random()*2 + 1
this.alpha = (Math.floor(Math.random()*10 + 1))/2/10
console.log(this.alpha)
this.color = "rgba(255, 255, 255, "+ this.alpha +")"
}
Start_item.prototype.draw = function () {
context.fillStyle = this.color
context.shadowBlur = this.r*3
context.beginPath()
context.arc(this.x, this.y, this.r, 2*Math.PI, false)
context.closePath()
context.fill()
}
function init () {
for (let i = 0; i < startNum; i ++) {
startArr[i] = new Start_item(i, Math.random()*WIDTH, Math.random()*HEIGHT)
startArr[i].draw()
}
}
init()
</script>
</body>
</html>
我学习的地址主要是菜鸟教程以及掘金,然后班门弄斧一下