The scroll function moves exponentially

I have a scroll function for my canvas that detects the distance moved by my mouse and shifts all my images to the canvas.

The problem is that I barely move the mouse and the number of offsets increases exponentially, and I'm not sure why ... this is my function that deals with the calculation of the offset:

canvas.addEventListener('mousedown', scrol_cnv, false); function scroll_cnv(e) { if (e.button == 2) {//right click only var x = e.pageX; // get click X var y = e.pageY; //get click Y function clear() { this.removeEventListener('mousemove', updt, false); } function updt(evt) { var difx = evt.pageX - x; var dify = evt.pageY - y; //this is where offset is becoming incorrect //offsets is globally defined `window.offsets = {}` offsets.cur_offsetx -= difx; offsets.cur_offsety -= dify; } this.addEventListener('mousemove', updt, false); this.addEventListener('mouseup', clear, false); } } 

Am I wrongly subtracting the offset?

+4
source share
1 answer

You want the offset to be based on the offset during mousedown . Events that often happen should not change without a framework.

You probably also want to remove your mouseup listener, otherwise you will get another click (no functional harm, just extra overhead).

 canvas.addEventListener('mousedown', scrol_cnv, false); function scroll_cnv(e) { if (e.button == 2) {//right click only var x = e.pageX; // get click X var y = e.pageY; //get click Y // store the initial offsets var init_offsetx = offsets.cur_offsetx; var init_offsety = offsets.cur_offsety; function clear() { this.removeEventListener('mousemove', updt, false); this.removeEventListener('mouseup', clear, false); } function updt(evt) { var difx = evt.pageX - x; var dify = evt.pageY - y; //this is where offset is becoming incorrect //offsets is globally defined `window.offsets = {}` offsets.cur_offsetx = init_offsetx - difx; offsets.cur_offsety = init_offsetx - dify; } this.addEventListener('mousemove', updt, false); this.addEventListener('mouseup', clear, false); } } 
+4
source

Source: https://habr.com/ru/post/1495149/


All Articles