I’m creating a map of sorts, using Html5 2d Canvas.
The main features are zooming, and dragging. My problem is dragging the map is very jerky. I don’t know if or how I could use requestAnimation frame, since it’s not an animation by my understanding?
I’ve optimised it so far so: 1) when zoomed out, fine details are not drawn unnecessarily – and 2) when zoomed in, drawable items outside the viewport are not drawn.
(I’m using JQuery except for canvas drawing). Currently, when the user triggers onmousedown, each mousemove event redraws the canvas, so dragging the map, i.e. changing what the user sees in the viewport.
So, simplified:
$(canvas).mousemove(function(e) {
if (mousedown){
dragger.update({x: e.pageX, y: e.pageY});
drawer.drawMap();
}
});
function MapDrawer(...){
this.drawMap = function(){
this.ctx.clearRect(0,0, this.canvasWidth, this.canvasHeight);
this.ctx.save();
this.ctx.transform(...); // map position and zoom
this.selectivelyDrawMapFeatures();
this.ctx.restore();
}
}
Could I improve this with requestAnimationFrame? I hope I’ve given enough information for someone to demonstrate with a bit of peudocode how this could be implemented, or improved.
Thanks
Yes you could use requestAnimationFrame. All requestAnimationFrame really does is execute a function, then redraw the screen. Basically the steps would be
*mousedown: start tracking the mouse’s position, and start redrawing your canvas via requestAnimationFrame like so
window.requestAnimationFrame(myRedrawFunction)*onmousemove: track the dragged objects position
*onmouseup: stop tracking/redrawing
Make sure the redraw function grabs the objects location from wherever you’re tracking (in other words, don’t rely on DOM, although being a canvas project I assume you’re not anyway)