Skip to content

Instantly share code, notes, and snippets.

@silviopaganini
Created March 7, 2013 18:07
Show Gist options
  • Save silviopaganini/5110269 to your computer and use it in GitHub Desktop.
Save silviopaganini/5110269 to your computer and use it in GitHub Desktop.
Distort Image CoffeeScript
class DistortImage
_w : null
_h : null
_hseg : null
_vseg : null
_p : null
_tri : null
_xMin : null
_xMax : null
_yMax : null
_hsLen : null
_vsLen : null
constructor : (w, h, hseg = 2, vseg = 2) ->
@_w = w
@_h = h
@_hseg = hseg
@_vseg = vseg
@init()
init : =>
@_p = []
@_tri = []
w2 = @_w / 2
h2 = @_h / 2
@_xMin = @_yMin = 0
@_xMax = @_w
@_yMax = @_h
@_hsLen = @_w / ( @_hseg + 1 )
@_vsLen = @_h / ( @_vseg + 1 )
# create points:
for ix in [0..@_vseg + 1]
for iy in [0..@_hseg + 1]
x = ix * @_hsLen
y = iy * @_vsLen
@_p.push( x: x, y: y, sx: x, sy: y )
# create triangles:
for ix in [0..@_vseg]
for iy in [0..@_hseg]
@_tri.push([ @_p[ iy + ix * ( @_hseg + 2 ) ] , @_p[ iy + ix * ( @_hseg + 2 ) + 1 ] , @_p[ iy + ( ix + 1 ) * ( @_hseg + 2 ) ] ] )
@_tri.push([ @_p[ iy + ( ix + 1 ) * ( @_hseg + 2 ) + 1 ] , @_p[ iy + ( ix + 1 ) * ( @_hseg + 2 ) ] , @_p[ iy + ix * ( @_hseg + 2 ) + 1 ] ] )
setTransform : (graphics, bmd, tl, tr, br, bl) =>
dx30 = bl.x - tl.x
dy30 = bl.y - tl.y
dx21 = br.x - tr.x
dy21 = br.y - tr.y
l = @_p.length
while --l> -1
point = @_p[ l ]
gx = ( point.x - @_xMin ) / @_w
gy = ( point.y - @_yMin ) / @_h
bx = tl.x + gy * ( dx30 )
_by = tl.y + gy * ( dy30 )
point.sx = bx + gx * ( ( tr.x + gy * ( dx21 ) ) - bx )
point.sy = _by + gx * ( ( tr.y + gy * ( dy21 ) ) - _by )
@render(graphics, bmd)
render : (graphics, bmd) =>
@_sMat = new createjs.Matrix2D()
@_tMat = new createjs.Matrix2D()
l = @_tri.length
graphics.clear()
while --l> -1
a = @_tri[ l ]
p0 = a[0]
p1 = a[1]
p2 = a[2]
x0 = p0.sx
y0 = p0.sy
x1 = p1.sx
y1 = p1.sy
x2 = p2.sx
y2 = p2.sy
u0 = p0.x
v0 = p0.y
u1 = p1.x
v1 = p1.y
u2 = p2.x
v2 = p2.y
@_tMat.tx = u0
@_tMat.ty = v0
@_tMat.a = ( u1 - u0 ) / @_w
@_tMat.b = ( v1 - v0 ) / @_w
@_tMat.c = ( u2 - u0 ) / @_h
@_tMat.d = ( v2 - v0 ) / @_h
@_sMat.a = ( x1 - x0 ) / @_w
@_sMat.b = ( y1 - y0 ) / @_w
@_sMat.c = ( x2 - x0 ) / @_h
@_sMat.d = ( y2 - y0 ) / @_h
@_sMat.tx = x0
@_sMat.ty = y0
@_tMat.invert()
@_tMat.prependMatrix( @_sMat )
# draw:
graphics.beginBitmapFill(bmd, "no-repeat", @_tMat)
graphics.moveTo( x0, y0 )
graphics.lineTo( x1, y1 )
graphics.lineTo( x2, y2 )
graphics.endFill()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment