summaryrefslogtreecommitdiff
path: root/draw.js
blob: 53cd67328bd3b816ed5ac50c3587aaaf0a6a281e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var draw = $(function(){
  var draw = {}
  
  var drawing = false, lastPoint
  var brushColor = 0, brushColors = ['#000','#888','#fff']

  var canvas = $('#imageColour').get(0)
  var ctx = canvas.getContext('2d')
  ctx.fillStyle = '#fff'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  var brush = document.querySelector('#brush')
  var brushCtx = brush.getContext('2d')
  resizeBrush(2, 2)
    
  function down(e) {
    drawing = true
    lastPoint = toCoord(e)
    stamp(lastPoint)
  }
  function move(e) {
    if (! drawing) return
    var point = toCoord(e)
    line(lastPoint, point)
    lastPoint = point
  }
  function up(e) {
    drawing = false
    render()
  }
  
  function toCoord(e) {
    return {
      x: e.pageX - canvas.offsetLeft,
      y: e.pageY - canvas.offsetTop,
    }
  }
  function line(a, b) {
    var len = dist(a.x, a.y, b.x, b.y)
    var bw = 1
    var x, y, i;
    for (var i = 0; i <= len; i += bw) {
      x = lerp(i / len, a.x, b.x)
      y = lerp(i / len, a.y, b.y)
      stamp({ x, y })
    }
  }
  function stamp(p) {
    var xx = Math.floor(p.x - brush.width/2)
    var yy = Math.floor(p.y - brush.height/2)
    ctx.drawImage(brush, xx, yy)
  }
  function resizeBrush(w, h) {
    brush.width = clamp(w, 1, 50)
    brush.height = clamp(h, 1, 50)
    brushCtx.fillStyle = brushColors[brushColor]
    brushCtx.fillRect(0, 0, brush.width, brush.height)
  }
  
  function lerp(n,a,b){ return (b-a)*n+a }
  function dist(x0,y0,x1,y1){ return Math.sqrt(Math.pow(x1-x0,2) + Math.pow(y1-y0,2)) }
  function clamp(n,a,b){ return n<a?a:b<n?b:n }

  $('#imageColour').on({
    mousedown: down,
    touchstart: untouch(down),
  })
  $('body').on({
    mousemove: move,
    touchmove: untouch(move),
    mouseup: up,
  })
  document.body.addEventListener('touchmove', function(e){
    e.preventDefault()
  })
  function untouch(f){ return (e) => f(e.originalEvent.touches[0]) }
  $('body').on('keydown', (e) => {
    if (e.target === input) return
    // console.log(e.keyCode)
    switch (e.keyCode) {
      case 39: // right
      case 38: // up
      case 221: // right bracket
        resizeBrush(brush.width+1, brush.height+1)
        break
      case 37: // left
      case 40: // down
      case 219: // left bracket
        resizeBrush(brush.width-1, brush.height-1)
        break
      case 88: // x
        brushColor = (brushColor + 1) % brushColors.length
        resizeBrush(brush.width, brush.height)
        break
    }
  })

  return draw
})