通过观察小提琴可能是最好的理解,但我想要实现的一般想法是一个平滑的卷轴,有各种各样的' snpping'吸引点。
用户将使用鼠标/触控板滚动创建一个delta值,然后将它们加在一起以提供目标值,从这里我可以向该值缓和(这是为了点击滚动的人鼠标轮)。滚动开始后我希望它能够捕捉到各个点。我已经计算出了对这些点的吸引力,但是当它从上面加入我的缓和时它并没有按照需要工作。
var aEl = document.getElementById('a');
var bEl = document.getElementById('b');
Sketch.create({
setup: function() {
this.range = {
min: 0,
max: 10000
};
this.easing = 0.1;
this.current = {
p: 0,
t: 0,
f: 0
};
this.attractors = [];
this.attractionRadius = (this.range.max / 5);
for (var i = 0, x = 0; x = i * (this.range.max / 4), i < 5; i++) {
this.attractors.push(x);
}
window.addEventListener('mousewheel', this.onMouse.bind(this));
},
draw: function() {
var w = (this.current.p / this.range.max) * this.width;
this.fillStyle = 'black';
this.fillRect(0, 0, w, this.height);
this.attractors.forEach(function(attractor) {
var x = (attractor / this.range.max) * this.width;
this.beginPath();
this.arc(x, this.height, 10, 0, Math.PI * 2, false);
this.fillStyle = 'red';
this.fill();
}.bind(this));
},
update: function() {
var _this = this;
this.attractors.forEach(function(attractor, index) {
var delta = attractor - _this.current.p;
var absDelta = Math.abs(delta);
if (absDelta < _this.attractionRadius) {
// calculate force toward each attraction point.
_this.current.f += delta * (1 - absDelta / _this.attractionRadius);
}
});
console.log(this.current, (this.current.t - this.current.p) * this.easing);
// add the easing to our forces, I think this is where the error lies?
this.current.f += (this.current.t - this.current.p) * this.easing;
this.current.p += this.current.f;
//reset the forces.
this.current.f = 0;
},
// set the target from the users scroll position, limited to the range set above.
onMouse: function(event) {
var delta = event.wheelDeltaY;
this.current.t += delta;
this.current.t =
this.current.t < this.range.min ? this.range.min :
this.current.t > this.range.max ? this.range.max :
this.current.t;
event.preventDefault();
}
});
&#13;
* {
margin: 0;
padding: 0;
}
&#13;
<script src="https://rawgit.com/soulwire/sketch.js/master/js/sketch.min.js"></script>
&#13;