View Full Version : Easiest way to move canvas in JS?

02-11-2016, 11:47 PM
I've made a tool (realruler.com) mostly for fun as my first attempt to code something relatively useful in JS.
I've also use w3css to make things responsive on various screen sizes.

The ruler in the upper part of the screen is basically coded in java script as a bunch of lines drawn on canvas. There's a special function which draws these lines along with ticks and everything else.
Now, let's just say I'd like to make this canvas "draggable" with mouse? Nothing fancy, just to be able to move it a bit up or down.

How to achieve that the easiest way?

Thanks a lot in advance.

02-18-2016, 10:14 PM
This question implies that this is done all the time and it is, just not with canvas as far as I know. However, your canvas is in a div, so that can be moved about easily enough in response to mouse or finger gestures. But, unless there already is a drag and drop api for canvas, which I doubt, I would think one would need to determine whether or not on touchstart/mousedown the coordinates were over the ruler and then, if so, until touchend/mouseup or for some reason (going offscreen somehow, as is possible, though that might want to be dealt with depending upon what ensues after that) tracking the movement of the pointing device and translating that into repositioning of this parent div, which would need to be positioned either absolutely or fixed for this to work. A placeholder div of the same or similar dimensions to that occupied by the ruler would also be needed to preserve the current layout, as once an element moves, unless it is fixed or absolute, everything else around it will also move, and unless there is a placeholder, it will initially be on top of something else in the layout.

That's sort of how i would go about it from scratch. Before we go down that road, see if this might work for you:


You can even try applying it to the canvas element itself, though I think it may have to be used on the canvas element's parent division.