//构造函数
function DynamicRectangle(o){
this.x=0,//原点坐标X
this.y=0,//原点坐标Y
this.x1=0,//X1坐标
this.y1=0,//Y1坐标
this.x2=0,//X2坐标
this.y2=0,//Y2坐标
this.x3=0,//X3坐标
this.y3=0,//Y3坐标
this.x4=0,//X4坐标
this.y4=0,//Y4坐标
this.init(o);
}
//初始化
DynamicRectangle.prototype.init=function(o){
for(var key in o){
this[key]=o[key];
}
}
//绘制线条
DynamicRectangle.prototype.drawLine=function(ctx,startX,startY,endX,endY){
ctx.save();
ctx.beginPath();
ctx.translate(this.x,this.y);//设定原点坐标
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
if(this.lineWidth){//线宽
ctx.lineWidth=this.lineWidth;
}
if(this.lineCap){
ctx.lineCap=this.lineCap;//线帽
}
if(this.stroke){//描边
this.strokeStyle?(ctx.strokeStyle=this.strokeStyle):null;
ctx.stroke();
}
ctx.restore();
}
//绘制
DynamicRectangle.prototype.render=function(context){
var ctx=context;
//绘制好4条线段
this.drawLine(ctx,this.x1,this.y1,this.x2,this.y2);//上边线
this.drawLine(ctx,this.x2,this.y2,this.x3,this.y3);//右边线
this.drawLine(ctx,this.x3,this.y3,this.x4,this.y4);//下边线
this.drawLine(ctx,this.x4,this.y4,this.x1,this.y1);//左边线
return this;
}
//创建方形
var rect = new DynamicRectangle({
x:7,//原点坐标x
y:2,//原点坐标y
x1:0,//方形左上角坐标x
y1:0,//方形左上角坐标y
x2:100,//方形右上角坐标x
y2:0,//方形右上角坐标y
x3:100,//方形右下角坐标x
y3:60,//方形右下角坐标y
x4:0,//方形左下角坐标x
y4:60,//方形左下角坐标y
lineWidth:1.5,//线宽
lineCap:'square',//线帽
stroke:true,//描边
strokeStyle:'palevioletred',//线的颜色
}).render(ctx);
效果如下:
var dir=1;//方向
var dis=2;//X轴移动初始值
move=function(){
//清理画布
ctx.clearRect(0,0,W,H);
rect.y2+=dis*dir;
rect.render(ctx);
}
timmer=setInterval(move,10);//开始任务
此时的效果是这样的
move=function(){
//清理画布
ctx.clearRect(0,0,W,H);
rect.y2+=dis*dir;
rect.render(ctx);
if(rect.y2>=60||rect.y2<=0){
dir=-dir;//改变方向
}
}
move=function(){
//清理画布
ctx.clearRect(0,0,W,H);
rect.y2+=dis*dir;
rect.y3+=-dis*dir;
rect.render(ctx);
if(rect.y2>=60||rect.y2<=0||rect.y3>=60||rect.y3<=0){
dir=-dir;//改变方向
}
}
move=function(){
//清理画布
ctx.clearRect(0,0,W,H);
if(animateDir=='right'){//长方形的右边在运动
rect.y2+=dis*dir;
rect.y3+=-dis*dir;
}else{//长方形的左边在运动
rect.y1+=dis*dir2;
rect.y4+=-dis*dir2;
}
rect.render(ctx);
if(animateDir=='right'){
if(rect.y2>=60||rect.y2<=0||rect.y3>=60||rect.y3<=0){
dir=-dir;
animateDir='left';//切换为左边运动
}
}else{
if(rect.y1>=60||rect.y1<=0||rect.y4>=60||rect.y4<=0){
dir2=-dir2;
animateDir='right';//切换为右边运动
}
}
}
此时效果如下: