viewer.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict'
  2. var mouseChange = require('mouse-change')
  3. var alphaShape = require('./alpha')
  4. var fit = require('canvas-fit')
  5. var alphaContainer = document.createElement('div')
  6. alphaContainer.style.top = '0'
  7. alphaContainer.style.left = '0'
  8. alphaContainer.style.position = 'absolute'
  9. alphaContainer.style['z-index'] = 10
  10. alphaContainer.style.color = '#fff'
  11. var alphaLabel = document.createElement('p')
  12. alphaContainer.appendChild(alphaLabel)
  13. var alphaSlider = document.createElement('input')
  14. alphaSlider.type = 'range'
  15. alphaSlider.minValue = 0
  16. alphaSlider.maxValue = 100
  17. alphaSlider.value = 1.0
  18. alphaContainer.appendChild(alphaSlider)
  19. document.body.appendChild(alphaContainer)
  20. var canvas = document.body.appendChild(document.createElement('canvas'))
  21. window.addEventListener('resize', fit(canvas))
  22. var context = canvas.getContext('2d')
  23. var points = []
  24. var pbuttons = 0
  25. mouseChange(function(buttons, x, y) {
  26. if(buttons&1 && (~pbuttons)&1) {
  27. points.push([x/canvas.width, y/canvas.height])
  28. }
  29. pbuttons = buttons
  30. })
  31. function render() {
  32. requestAnimationFrame(render)
  33. alphaLabel.innerHTML = 'alpha = ' + alphaSlider.value
  34. var alphaHull = alphaShape(+alphaSlider.value, points)
  35. var w = canvas.width
  36. var h = canvas.height
  37. context.fillStyle = '#000'
  38. context.fillRect(0, 0, canvas.width, canvas.height)
  39. context.strokeStyle = '#f00'
  40. for(var i=0; i<alphaHull.length; ++i) {
  41. var cell = alphaHull[i]
  42. for(var j=0; j<cell.length; ++j) {
  43. var p = points[cell[j]]
  44. var q = points[cell [(j+1)%cell.length]]
  45. context.beginPath()
  46. context.moveTo(w * p[0], h * p[1])
  47. context.lineTo(w * q[0], h * q[1])
  48. context.stroke()
  49. }
  50. }
  51. context.fillStyle = '#0f0'
  52. for(var i=0; i<points.length; ++i) {
  53. var p = points[i]
  54. context.fillRect(p[0]*w, p[1]*h, 5, 5)
  55. }
  56. }
  57. render()