# Smooth drag scrolling of an Isometric map - Html5

I have implemented a basic Isometric tile engine that can be explored by dragging the map with the mouse. Please see the fiddle below and drag away:

http://jsfiddle.net/kHydg/14/

The code broken down is (CoffeeScript):

The draw function

draw = ->
requestAnimFrame draw
canvas.width = canvas.width

for row in [0..width]
for col in [0..height]
xpos = (row - col) * tileHeight + width
xpos += (canvas.width / 2) - (tileWidth / 2) + scrollPosition.x
ypos = (row + col) * (tileHeight / 2) + height + scrollPosition.y
context.drawImage(defaultTile, Math.round(xpos), Math.round(ypos), tileWidth, tileHeight)


Mouse drag-scrolling control

scrollPosition =
x: 0
y: 0

dragHelper =
active: false
x: 0
y: 0

handleMouseDown(e)
, false

handleDrag(e)
, false

handleMouseUp(e)
, false

handleDrag = (e) =>
e.preventDefault()
if dragHelper.active
x = e.clientX
y = e.clientY
scrollPosition.x -= Math.round((dragHelper.x - x) / 28)
scrollPosition.y -= Math.round((dragHelper.y - y) / 28)

handleMouseUp = (e) =>
e.preventDefault()
dragHelper.active = false

handleMouseDown = (e) =>
e.preventDefault()
x = e.clientX
y = e.clientY
dragHelper.active = true
dragHelper.x = x
dragHelper.y = y


The Problem

As you can see from the fiddle the dragging action is ok but not perfect. How would I change the code to make the dragging action more smooth? What I would like is the point of the map you click on to stay under the mouse point whilst you drag; the same as they have done here: http://craftyjs.com/demos/isometric/

To move smoother, change

scrollPosition.x -= Math.round((dragHelper.x - x) / 28)
scrollPosition.y -= Math.round((dragHelper.y - y) / 28)


to

scrollPosition.x = Math.round((x - dragHelper.x))
scrollPosition.y = Math.round((y - dragHelper.y))


To prevent jumping when first clicking on it, change

 dragHelper.x = x
dragHelper.y = y


to

 dragHelper.x = x - scrollPosition.x
dragHelper.y = y - scrollPosition.y


And you should be fine.

Not sure why the / 28, did you want it snap to grid?

• Very good, works perfectly. Thank you very much :) The / 28 was to reduce the speed of the grid movement. If only I had > 15 rep then I could up arrow you. Somebody up arrow user18474's answer :p – Jamie Fearon Aug 30 '12 at 20:31