from AppKit import NSTimer from vanilla import Window from mojo.canvas import Canvas from mojo.drawingTools import fill, rect from mojo.tools import CallbackWrapper class CanvasAnimationExample: width = 500 height = 400 pos = 0, 0 size = 100 steps = 5 framesPerSecond = 30 interval = framesPerSecond / 1000. addHorizontal = True directionX = 1 directionY = 1 def __init__(self): self.w = Window((self.width, self.height)) self.w.canvas = Canvas((0, 0, self.width, self.height), delegate=self, canvasSize=(self.width, self.height)) self.w.open() self._callback = CallbackWrapper(self.redraw) self.scheduleTimer() def scheduleTimer(self): if self.w.getNSWindow() is not None: self.trigger = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(self.interval, self._callback, "action:", None, False) def redraw(self, timer): self.w.canvas.update() self.scheduleTimer() def draw(self): x, y = self.pos if self.addHorizontal: x += self.steps * self.directionX else: y += self.steps * self.directionY if x > (self.width - self.size): self.addHorizontal = False x = self.width - self.size self.directionX *= -1 elif x < 0: self.addHorizontal = False x = 0 self.directionX *= -1 if y > (self.height - self.size): self.addHorizontal = True y = self.height - self.size self.directionY *= -1 elif y < 0: self.addHorizontal = True y = 0 self.directionY *= -1 fill(x / float(self.width), y / float(self.height), 1) rect(x, y, self.size, self.size) self.pos = x, y CanvasAnimationExample()