Animation in mojo.Canvas



  • Hi Frederik,

    I'd like to know if it is possible to generate an animation into a mojo.Canvas instance or into an NSView() (a kind of Processing void draw{}, which refresh itself to a given rate).

    I'd like to create something similar to the responsive lettering by Erik but keeping the animation into the application environment (no svg, no html).

    Any idea?

    All the best



  • OMG
    you made my day

    Thanks : )))))


  • admin

    Hi Roberto

    small example

    hope this helps :)

    from AppKit import NSTimer
    from random import random
    
    from vanilla import *
    
    from mojo.canvas import Canvas
    import mojo.drawingTools as dt
    
    from lib.baseObjects import CallbackWrapper
    
    class Test(object):
        
        def __init__(self):
            self.pos = 0, 0
            self.width = 400
            self.height = 400
            self.size = 100
            self.steps = 5
            self.addHorizontal = True
            self.directionX = 1
            self.directionY = 1
            
            framePerSecond = 30
            
            self.interval = framePerSecond / 1000.
            
            self.w = Window((400, 400))
            
            self.w.canvas = Canvas((0, 0, 400, 400), self, canvasSize=(self.width, self.height))
            self.w.open()
            
            self._callback = CallbackWrapper(self.redraw)
            self.sheduleTimer()
        
        def sheduleTimer(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.sheduleTimer()
        
        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
            
            dt.fill(x/float(self.width), y/float(self.height), 1)
            dt.rect(x, y, self.size, self.size)
            
            self.pos = x, y
    
    Test()