Created
September 16, 2013 20:57
-
-
Save Beyamor/6586504 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Canvas | |
constructor: (@width, @height) -> | |
@el = $ "<canvas>" | |
@context = @el[0].getContext "2d" | |
@el.width width | |
@el.height height | |
@context.canvas.width = width | |
@context.canvas.height = height | |
$("body").append @el | |
drawRect: ({x: x, y: y, width: width, height: height, color: color}) -> | |
@context.beginPath() | |
@context.fillStyle = color | |
@context.fillRect x, y, width, height | |
clear: -> | |
@drawRect { | |
x: 0 | |
y: 0 | |
width: @width | |
height: @height | |
color: "white" | |
} | |
class Box | |
constructor: (@canvas, x, y, @width, @height) -> | |
@setPos {x: x, y: y} | |
containsPoint: ({x: x, y: y}) -> | |
(x >= @x - @width/2) and (x <= @x + @width/2) and | |
(y >= @y - @height/2) and (y <= @y + @height/2) | |
setPos: ({x: x, y: y}) -> | |
@x = x | |
@y = y | |
@redraw() | |
redraw: -> | |
@canvas.clear() | |
@canvas.drawRect { | |
x: @x - @width/2 | |
y: @y - @height/2 | |
width: @width | |
height: @height | |
color: "red" | |
} | |
relativePos = (e, el) -> | |
relX = e.pageX - el.parent().offset().left | |
relY = e.pageY - el.parent().offset().top | |
return {x: relX, y: relY} | |
watchForDragging = (box, el) -> | |
isBeingDragged = false | |
el.bind "mousedown", (e) -> | |
pos = relativePos e, el | |
if box.containsPoint pos | |
isBeingDragged = true | |
box.setPos pos | |
el.bind "mousemove", (e) -> | |
if isBeingDragged | |
box.setPos relativePos e, el | |
el.bind "mouseup", (e) -> | |
isBeingDragged = false | |
$ -> | |
canvas = new Canvas 640, 480 | |
box = new Box canvas, 0, 0, 50, 50 | |
watchForDragging box, canvas.el |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment