Move box by drag & drop with Snap.svg

Snap.svgをつかってボックスをdrag&dropで動かす

by bc_rikko

HTML

<script src="https://rawgit.com/adobe-webplatform/Snap.svg/master/dist/snap.svg-min.js"></script>
<button id="add" type="button">add</button>

JavaScript

const s = Snap(800, 800)

const createBox = (paper, target) => {
	const box = paper
  	.rect(
    	target.x,
      target.y,
      target.width,
      target.height
    )
    .attr({
			fill: '#333'
		})
  
  box.node.id = target.id
  // onMove, onStart, onEndを指定しなくてもドラッグできる
  // Raphaëlだとドラッグ中にboxが重なると動作がおかしくなるがSnapは大丈夫
  box.drag()
  box.dblclick(removeBox)
  return box
}

let count = 0
const objectMap = []

const removeBox = event => {
	const box = objectMap[event.target.id]
  box.remove()
}
document.getElementById('add').addEventListener('click', () => {
	const box = createBox(s, {
  	x: 100,
    y: 100,
    width: 100,
    height: 100,
    id: `box-${count}`
  })
  
  objectMap[`box-${count}`] = box
  count++
})