Skip to content

0M Rendering a group of objects

Luis Murillo Baltodano edited this page Aug 29, 2021 · 2 revisions

How to use renderGroup

First you need an array like

Array [
    homogeneousShape // it can be any of these shape types: rect | img | txt | arc | lines
]

All the shapes in the array have to match the same type within its properties

Use the renderGroup function

renderGroup(
    shapeType,
    homogeneousShapes,
    beforeRenderCallback,
    AfterRenderCallback
)

'Before' and 'after' render callbacks both receive the current object that iterator it is iterating trough and its index in the group (perfect for updating the shape before and/or after its rendering)

Example

import preset from 'https://luisarmando-testcoder.github.io/canvas-preset/index.js'

const mySquareObjectGroup = [{
    x: 100,
    y: 20,
    width: 50,
    height: 50,
    color: '#44f',
    rotation: 5,
    acceleration: 2
}, {
    x: 100,
    y: 20,
    width: 150,
    height: 20,
    color: '#f44',
    rotation: 275,
    acceleration: 1
}]

const moveSquare = (object, index) => {
    object.x += object.acceleration * (index + 1)
    object.rotation++
}

function bounceSquare(object, index) {
    const isOutOfCanvas = object.x + object.width / 2 > this.width ||
                          object.x - object.width / 2 < 0
    if (isOutOfCanvas) object.acceleration = -object.acceleration
}

preset(({size, renderGroup, c, draw, clear}) => {
    size()
    draw(() => {
        clear()
        renderGroup(
            'rect',
            mySquareObjectGroup,
            moveSquare.bind(c),
            bounceSquare.bind(c)
        )
    })
})
Clone this wiki locally