1. 创建canvas画布
1.1 在body标签内创建canvas标签,并添加id元素。
<canvas id="mycanvas"></canvas>
1.2 在script标签中获取dom元素canvas, 并进行设置,第二行为固定写法。
var canvas = document.querySelector("#mycanvas")
var ctx = canvas.getContext('2d')
1.3 设置画布的宽高分别等于屏幕大小的宽高,宽高分别减10用以呈现完整的画布。
canvas.width = document.documentElement.clientWidth - 10
canvas.height = document.documentElement.clientHeight - 10
1.4 在head头部标签设置画布的样式。
<style>
* {
margin: 0;
padding: 0;
}
canvas {
display: block;
margin: 0 auto;
}
</style>
2. 封装小球的构造函数
function Ball() {
this.randomX = Math.ceil(Math.random() * canvas.width)
this.randomY = Math.ceil(Math.random() * canvas.height)
this.r = 10
this.color = 'pink'
this.dx = Math.ceil(Math.random() * 10) - 5
this.dy = Math.ceil(Math.random() * 10) - 5
this.index = ballArr.length
if (this.randomX < this.r) {
this.x = this.r
}else if(this.randomX > canvas.width - this.r) {
this.x = canvas.width - this.r
}else {
this.x = this.randomX
}
if (this.randomY < this.r) {
this.y = this.r
}else if(this.randomY > canvas.height - this.r) {
this.y = canvas.height - this.r
}else {
this.y = this.randomY
}
ballArr.push(this)
}
2.1 设置生成小球的随机坐标。
this.randomX = Math.ceil(Math.random() * canvas.width)
this.randomY = Math.ceil(Math.random() * canvas.height)
根据画布的宽高来随机生成小球x,y的坐标,Math.ceil()为向上取整,也可使用Math.floor()同parseInt()向下取整。
2.2 设置小球的半径及颜色。
this.r = 10
this.color = 'pink'
2.3 设置小球的运动方向。
this.dx = Math.ceil(Math.random() * 10) - 5
this.dy = Math.ceil(Math.random() * 10) - 5
生成的数字为1~10之间,需要将生成的数字减5,x轴为负数的球就会往左移动,正数往右;y轴负数往上,正数往下,从而能够达到小球向四面八方运动的一个效果。
2.4 判断小球随机生成的坐标是否让小球在画布之内。
if (this.randomX < this.r