Skip to content

Instantly share code, notes, and snippets.

@jarek-foksa
Last active August 29, 2015 13:55
Show Gist options
  • Select an option

  • Save jarek-foksa/8779392 to your computer and use it in GitHub Desktop.

Select an option

Save jarek-foksa/8779392 to your computer and use it in GitHub Desktop.
RectShape =
$element: null
width: 100
height: 100
x: 0
y: 0
r1: 0 # top left
r2: 0 # top right
r3: 0 # bottom left
r4: 0 # bottom right
init: ->
@$element = svg 'path'
@$element.setAttribute 'boxy:shape', 'rect'
@$element.setAttribute 'boxy:x', @x
@$element.setAttribute 'boxy:y', @y
@$element.setAttribute 'boxy:width', @width
@$element.setAttribute 'boxy:height', @height
@$element.setAttribute 'boxy:r1', @r1
@$element.setAttribute 'boxy:r2', @r2
@$element.setAttribute 'boxy:r3', @r3
@$element.setAttribute 'boxy:r4', @r4
@_redraw()
return @
initWithRect: ($rect) ->
r = $rect.rx.baseVal.value
@width = $rect.width.baseVal.value
@height = $rect.height.baseVal.value
@x = $rect.x.baseVal.value
@y = $rect.y.baseVal.value
@r1 = r
@r2 = r
@r3 = r
@r4 = r
@init()
for attribute in ['style', 'transform']
@$element.setAttribute attribute, $rect.getAttribute(attribute)
return @
initWithPath: ($path) ->
@$element = $path
@width = parseFloat $path.getAttribute('boxy:width')
@height = parseFloat $path.getAttribute('boxy:height')
@x = parseFloat $path.getAttribute('boxy:x')
@y = parseFloat $path.getAttribute('boxy:y')
@r1 = parseFloat $path.getAttribute('boxy:r1')
@r2 = parseFloat $path.getAttribute('boxy:r2')
@r3 = parseFloat $path.getAttribute('boxy:r3')
@r4 = parseFloat $path.getAttribute('boxy:r4')
return @
free: ->
@$element.remove()
setX: (x) ->
@x = x
@$element.setAttribute 'boxy:x', x
@_redraw()
setY: (y) ->
@y = y
@$element.setAttribute 'boxy:y', y
@_redraw()
setWidth: (width) ->
@width = width
@$element.setAttribute 'boxy:width', width
@_redraw()
setHeight: (height) ->
@height = height
@$element.setAttribute 'boxy:height', height
@_redraw()
setR1: (r1) ->
@r1 = r1
@$element.setAttribute 'boxy:r1', r1
@_redraw()
setR2: (r2) ->
@r2 = r2
@$element.setAttribute 'boxy:r2', r2
@_redraw()
setR3: (r3) ->
@r3 = r3
@$element.setAttribute 'boxy:r3', r3
@_redraw()
setR4: (r4) ->
@r4 = r4
@$element.setAttribute 'boxy:r4', r4
@_redraw()
_redraw: ->
r1 = @_clampR @r1
r2 = @_clampR @r2
r3 = @_clampR @r3
r4 = @_clampR @r4
d = """
M #{@x + r1} #{@y}
L #{@x + @width - r2} #{@y}
A #{r2} #{r2} 0 0 1 #{@x+@width} #{@y+r2}
L #{@x+@width} #{@y+@height-r4}
A #{r4} #{r4} 0 0 1 #{@x+@width-r4} #{@y+@height}
L #{@x+r3} #{@y+@height}
A #{r3} #{r3} 0 0 1 #{@x} #{@y+@height-r3}
L #{@x} #{@y+r1}
A #{r1} #{r1} 0 0 1 #{@x+r1} #{@y}
"""
@$element.setAttribute 'd', d.replaceAll('\n', ' ')
_clampR: (r) ->
if r > (@width / 2)
r = @width / 2
else if r > (@height / 2)
r = @height / 2
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment