1、首先创建页面上下文关联
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
2、面向对象,JavaScript不区分类和实例的概念,而是通过原型(prototype)来实现面向对象编程;
具体详情查看https://www.liaoxuefeng.com/wiki/1022910821149312/1023022126220448
将公共的属性和方法写在原型上;
function Circle(x,y,r,color){
this.x=x;
this.y=y;
this.r=r;
this.color=color;
}
// Circle.prototype.leixing='创建小球';//
//创建小球 画圆
Circle.prototype.render=function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
ctx.fillStyle=this.color;
ctx.fill();
}
3、多个小球,可以用数组存储,注意元素的无序性;
var arr=[new Circle(200,210,30,'yellowgreen'),new Circle(50,100,30,'orange'),new Circle(70,180,30,'pink'),new Circle(100,100,30,'orange')];
//x轴坐标排序:a.因为x轴的位置决定了谁先出去,因为半径相同 b.如果半径不一样,还要进行一次半径的排序
function sort(){
arr.sort(function(a,b){
return a.x- b.x;
});
}
sort();
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#canvas{
border:1px solid #999;
}
</style>
</head>
<body>
<canvas id='canvas' width="600" height="400"></canvas>
<!-- <script src='undeerscore.min.js'></script> -->
<script>
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var timer=null;
//面向对象:js 单例模式 工厂模式 构造函数 原型链
//对象:构造函数里面 可以方式 属性 和方法, 公共的 构造函数的原型上 prototype 指向原型
//创建小球 :小球的圆心点 半径 颜色 都是属性 并且是可变的
// 画圆公共的方法:prototype
function Circle(x,y,r,color){
this.x=x;
this.y=y;
this.r=r;
this.color=color;
}
// Circle.prototype.leixing='创建小球';//
//创建小球 画圆
Circle.prototype.render=function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
ctx.fillStyle=this.color;
ctx.fill();
}
//创建方法 运动从左向右
Circle.prototype.run=function(){
//清除计时器 ---当小球移出去后
if(this.x>=canvas.width+this.r){
arr.pop();
if(arr.length==0){
clearInterval(timer);
console.log('over');
}
}
//多个小球 我们去清空的时候:如果当前的满足出去了,把 它从数组里面删除
//splice(下标开始的位置,数量);删除
// console.log(this.x,canvas.width+this.r);
/*if(this.x>canvas.width+this.r){
arr=_.without(arr,this);
console.log(arr.length);
if(arr.length==0){
clearInterval(timer);
}
}*/
this.x+=10;
}
//使用 实例化 new创建
//用数组 存储小球:注意元素的无序性
//var arr=[new Circle(50,100,30,'orange'),new Circle(100,100,30,'orange'),new Circle(70,180,30,'pink'),new Circle(200,210,30,'yellowgreen')];
var arr=[new Circle(200,210,30,'yellowgreen'),new Circle(50,100,30,'orange'),new Circle(70,180,30,'pink'),new Circle(100,100,30,'orange')];
//x轴坐标排序:a.因为x轴的位置决定了谁先出去,因为半径相同 b.如果半径不一样,还要进行一次半径的排序
function sort(){
arr.sort(function(a,b){
return a.x- b.x;
});
}
sort();
timer=setInterval(move,200);
function move(){
//清空画布
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<arr.length;i++){
arr[i].render();
arr[i].run();
}
// _.map(arr,function(e){
// e.render();
// e.run();
// })
}
</script>
</body>
</html>
效果图: