Smooth drag scrolling of an Isometric map - Html5
- by user881920
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
window.addEventListener 'mousedown', (e) =>
handleMouseDown(e)
, false
window.addEventListener 'mousemove', (e) =>
handleDrag(e)
, false
window.addEventListener 'mouseup', (e) =>
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/