这次看一个有趣的效果,将"一行三角形的总个数"调至1,2时,是最让我震惊的。
https://codepen.io/xiaodun/pen/PyxoaW?editors=0010
看到代码后,发现只是因为画的方向不同,然后体现出这种错位。
填充元素的逻辑:
if(this.isStart && this.data.length == 0){
for (var i = 0; i <= this.count; i++) {
this.data[i] = {};
this.data[i].x = (i / this.count) * this.width;
if (i % 2) {
this.data[i].y = 5;
} else {
this.data[i].y = this.height - 5;
}
}
this.h1 = -this.height;
this.h2 = this.height;
}
上述数据中的i % 2只是为了y轴坐标有不同,画上面的三角形和画下面的三角形都是用同一组数据。
运动逻辑
if (this.isStart) {
this.h1 += this.height / this.base1;
this.h2 -= this.height / this.base2;
if (this.h1 >= 0) {
this.h1 = 0;
}
if (this.h2 <= 0) {
this.h2 = 0;
}
} else {
this.h1 -= this.height / 20;
this.h2 += this.height / 20;
if (this.h1 <= -this.height) {
this.h1 = -this.height;
}
if (this.h2 >= this.height) {
this.h2 = this.height;
}
}
正反向以及临界值处理,到达临界值时不再变化y轴坐标
重点是画的逻辑
this.pen.beginPath();
this.pen.moveTo(0, -this.height);
this.pen.clearRect(0,0,this.width,this.height);
for(let i=0;i<this.data.length;i++){
let item = this.data[i];
this.pen.lineTo(item.x, item.y + this.h1);
}
this.pen.lineTo(this.width, -this.height);
this.pen.closePath();
this.pen.fill();
this.pen.beginPath();
this.pen.moveTo(0, this.height);
for (var i = 0; i < this.data.length; i++) {
let item = this.data[i];
this.pen.lineTo(item.x, item.y + this.h2);
}
this.pen.lineTo(this.width, this.height);
this.pen.closePath();
this.pen.fill();
上述代码大概是这样子