JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
track changes, merge paths, show line to mouse, etc
[crayon_mockup.git] / auto.coffee
1 # settings
2 width = 500
3 height = 500
4
5 # globals
6 $svg = null # jquery object for svg element
7 svg = null # dom object for svg element
8 selection = null
9 svg_ns = 'http://www.w3.org/2000/svg'
10 mouse = [0,0]
11
12 update_path = (path, data, flags) ->
13         d = ''
14         for loc, i in data
15                 if i is 0
16                         d += 'M '
17                 else
18                         d += ' L '
19                 d += "#{loc[0]} #{loc[1]}"
20         if flags?.to_mouse?
21                 d += "L #{mouse[0]} #{mouse[1]}"
22         if flags?.close?
23                 d += " z"
24         path.setAttribute "d", d
25
26 stop_drawing = ->
27         if selection?
28                 update_path selection.element, selection.data
29         selection = null
30         return false
31 stop_close_drawing = ->
32         if selection?
33                 update_path selection.element, selection.data, close: true
34         selection = null
35         return false
36 click = (x, y) ->
37         unless selection?
38                 path = document.createElementNS svg_ns, "path"
39                 selection = data: [], element: path
40                 svg.appendChild path
41         selection.data.push [x, y]
42         update_path selection.element, selection.data
43 mousemove = (x, y) ->
44         mouse[0] = x
45         mouse[1] = y
46         if selection?
47                 update_path selection.element, selection.data, to_mouse: true
48
49 # called automatically on domcontentloaded
50 init = ->
51         $container = $ '.crayon_mockup'
52         $stop_button = $ '<span class="button">stop drawing</span>'
53         $stop_close_button = $ '<span class="button">stop drawing, close loop</span>'
54         $tools = $ '<div class="toolbar"></div>'
55         $tools.append $stop_button
56         $tools.append $stop_close_button
57         $stop_button.click stop_drawing
58         $stop_close_button.click stop_close_drawing
59         $container.append $tools
60         svg = document.createElementNS svg_ns, 'svg'
61         svg.setAttribute 'width', width
62         svg.setAttribute 'height', height
63         svg.setAttribute 'viewBox', "0 0 #{width} #{height}"
64         $svg = $ svg
65         $container.append $svg
66         $svg.mousedown (e) ->
67                 offset = $svg.offset()
68                 click e.pageX - offset.left, e.pageY - offset.top
69                 return false
70         $svg.mousemove (e) ->
71                 offset = $svg.offset()
72                 mousemove e.pageX - offset.left, e.pageY - offset.top
73
74 $ init