Create a Side-to-Side Draggable HTML5 Canvas in a Div

I have been playing with Pixastic and a little bit of HTML5 canvas image manipulation for a site I’m working on. I load an image into an HTML5 canvas and let the user do some basic manipulation, including zooming in on the image.

Zooming in on the image quickly causes the canvas to outgrow my browser window. The div around the canvas is set to use overflow: auto so that the growing canvas doesn’t disrupt the rest of the page flow.

<div id="pageimgdiv" style="max-width: 100%; overflow: auto;">
   <canvas> 
      Your browser doesn't support HTML5 Canvas
   </canvas>
</div>

The overflowed div gains horizontal scrollbars (but not vertical ones, since there’s no max-height in my case). Unfortunately many people, including myself, don’t have horizontal scrolling configured for their mouse which means scrolling down to the scrollbar, moving over, then scrolling back up.

JQuery To The Rescue

I was able to use JQuery and the scrollLeft() function to make the canvas dragable within the div. The canvas itself doesn’t change sizes or pan (which would require a second canvas used as a buffer, I think). Instead we get the mouse position and current scrollLeft setting when the mouse is clicked, and then scroll more as they move the mouse, until they release the mouse or until they leave the wrapper div.

I’m using JQuery 1.7.2.

$(document).ready(function(){
    $('#pageimgdiv').on(
    {
	mousedown: function(clicke){
	    origX = clicke.pageX + $('#pageimgdiv').scrollLeft();
	    $('#pageimgdiv').on(
	    {
		mousemove : function(e){
		    curX = e.pageX + $('#pageimgdiv').scrollLeft();
		    var diff = (origX - curX);
		    var newpos = $('#pageimgdiv').scrollLeft() + diff;
		    if(newpos > ($('canvas').width() - $('#pageimgdiv').width())){
			newpos = ($('canvas').width() - $('#pageimgdiv').width());
		    }
		    if(newpos < 0){
			newpos = 0;
		    }
		    $('#pageimgdiv').scrollLeft(newpos);
		}
	    }
	    );
	},
	mouseleave: function(){
	    $('#pageimgdiv').off('mousemove');
	},
	mouseup: function(){
	    $('#pageimgdiv').off('mousemove');
	},
	click: function(){
	    $('#pageimgdiv').off('mousemove');
	}
    }
    );
});

Embrace and Extend

This code only scrolls horizontally. You could easily extend it to use scrollTop() and enable vertical scrolling as well.

This entry was posted in Computers, Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *