cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div class="wrapper">
    <div class="container">
        <h1>Animating the <a href="https://en.wikipedia.org/wiki/Barnsley_fern" target="_blank">Barnsley fern</a>
        </h1>
        <div class="row">
            <div class="col-lg-6">
                <canvas id="canvas"></canvas>
            </div>
            <div class="col-lg-6" id="controls">
                <p>Currently animating
                    <span id="current">Loading...</span>
                </p>
                <p>Scaling
                    <span id="scaling">Loading...</span>
                </p>
                <p>Transformation matrix
                    <span id="matrix">Loading...</span>
                </p>
                <p>Number of iterations
                    <input id="iterations" type="number" min="100" max="5000" name="iterations" value="1000">
                </p>
                <p>Watch and ponder...
                    <button id="pause">Pause</button>
                </p>
                <p>More
                    <a href="https://www.chradams.co.uk/fern/maker.html" target="_blank">Another cool generator here</a>
                </p>
            </div>
        </div>
    </div>
</div>
            
          
!
            
              @import url('https://fonts.googleapis.com/css?family=Jua|Roboto')

$background: #f7f1e3
$text: #aaa69d
$dark-text: darken($text, 15%)

*
    box-sizing: border-box

html,
body
    // Sizing
    padding: 0
    margin: 0
    width: 100%
    height: 100%
    background: $background

.wrapper
    // Flex
    height: 100%
    display: flex
    justify-content: center
    align-items: center
    // Stylez
    font-family: sans-serif
    color: $text
    font-family: 'Roboto', sans-serif

    .container
        // Fix flex overflow issues
        margin: auto

        h1
            font-size: 3rem
            font-family: 'Jua', sans-serif
            text-transform: uppercase
            text-align: center

            a
                font-family: inherit
                font-size: inherit
                text-decoration: inherit
                color: $dark-text

        .row
            canvas
                flex: 0 0 auto
                display: block
                margin: 0 auto
                width: 500px
                max-width: 100%
                background: transparent

            #controls
                input
                    width: 100px

                p
                    margin-top: 0
                    text-align: center

                    span,
                    input,
                    button,
                    a
                        border: none
                        display: block
                        margin: 0 auto
                        font-family: 'Jua', sans-serif
                        font-size: 1.5rem
                        text-decoration: none
                        color: $dark-text
                        background: transparent

                    input,
                    button
                        padding: 0
                        // border-bottom: 0.1rem solid $text

                    button
                        cursor: pointer

                    #matrix
                        font-size: 0.8rem
                        font-family: monospace
                        white-space: pre

            
          
!
            
              //
// CONSTANTS
//

// Fern transform matrices source
// https://www.chradams.co.uk/fern/maker.html
// Added a scaling factor as the last coefficient
const FERNS = [
    {
        name: 'Barnsley fern',
        coefs: [[0, 0, 0, 0.16, 0, 0, 0.01, 1],
            [0.85, 0.04, -0.04, 0.85, 0, 1.6, 0.85, 1],
            [0.2, -0.26, 0.23, 0.22, 0, 1.6, 0.07, 1],
            [-0.15, 0.28, 0.26, 0.24, 0, 0.44, 0.07, 1]]
    },
    // {
    //     name: 'Cyclosorus',
    //     coefs: [[0, 0, 0, 0.25, 0, -0.4, 0.02, 1.2],
    //         [0.95, 0.005, -0.005, 0.93, -0.002, 0.5, 0.84, 1.2],
    //         [0.035, -0.2, 0.16, 0.04, -0.09, 0.02, 0.07, 1.2],
    //         [-0.04, 0.2, 0.16, 0.04, 0.083, 0.12, 0.07, 1.2]]
    // },
    // {
    //     name: 'Modified Barnsley fern',
    //     coefs: [[0, 0, 0, 0.2, 0, -0.12, 0.01, 1],
    //         [0.845, 0.035, -0.035, 0.82, 0, 1.6, 0.85, 1],
    //         [0.2, -0.31, 0.255, 0.245, 0, 0.29, 0.07, 1],
    //         [-0.15, 0.24, 0.25, 0.20, 0, 0.68, .07, 1]]
    // },
    {
        name: 'Cultica',
        coefs: [[0, 0, 0, 0.25, 0, -0.14, 0.02, 1],
            [0.85, 0.02, -0.02, 0.83, 0, 1, 0.84, 1],
            [0.09, -0.28, 0.3, 0.11, 0, 0.6, 0.07, 1],
            [-0.09, 0.28, 0.3, 0.09, 0, 0.7, 0.07, 1]]
    },
    {
        name: 'Fishbone',
        coefs: [[0,  0,  0, 0.25, 0, -0.4, 0.02, 1.2],
            [0.95, 0.002, -0.002, 0.93, -0.002, 0.5, 0.84, 1.2],
            [0.035, -0.11, 0.27, 0.01, -0.05, 0.005, 0.07, 1.2],
            [-0.04, 0.11, 0.27, 0.01, 0.047, 0.06, 0.07, 1.2]]
    },
    {
        name: 'Fractal tree',
        coefs: [[0, 0, 0, 0.5, 0, 0, 0.05, 16],
            [0.42, -0.42, 0.42, 0.42, 0, 0.2, 0.4, 16],
            [0.42, 0.42, -0.42, 0.42, 0, 0.2, 0.4, 16],
            [0.1, 0, 0, 0.1, 0, 0.2, 0.15, 16]]
    },
    {
        name: 'Golden Bee',
        coefs: [[0.6178, 0, 0, -0.6178, 0, 1, 0.5, 6],
            [0, -0.786, 0.786, 0, 0.786, 0, 0.5, 6],
            [0, 0, 0, 0, 0, 0, 0, 6],
            [0, 0, 0, 0, 0, 0, 0, 6]]
    }
]

const ZOOM = 18
const WIDTH = 250, HEIGHT = 200
const DWIDTH = 0.5, DHEIGHT = 0.95
const SPEED = 1/150
let ITERATIONS = 1e3

const DOM = {
    canvas: document.getElementById('canvas'),
    controls: {
        current: document.getElementById('current'),
        iterations: document.getElementById('iterations'),
        scaling: document.getElementById('scaling'),
        pause: document.getElementById('pause'),
        matrix: document.getElementById('matrix')
    }
}

//
// DRAW
//

function drawFern() {
    // Clear the canvas
    ctx.clearRect(-WIDTH*DWIDTH, -HEIGHT*DHEIGHT, WIDTH, HEIGHT)

    // Init the coords
    let coords = [0, 0]

    // Generate the coefficients for this frame
    let progress = (Math.cos(FRAMES*SPEED*Math.PI) + 1) / 2
    let coefs = []
    let coefs1 = FERNS[CYCLE%FERNS.length].coefs
    let coefs2 = FERNS[(CYCLE+1)%FERNS.length].coefs
    for (let i=0; i<coefs1.length; i++) {
        coefs[i] = []
        for (let j=0; j<coefs1[i].length; j++) {
            coefs[i][j] = coefs1[i][j]*progress + coefs2[i][j]*(1-progress)
        }
    }

    // Switch the cycle every multiple of PI
    if (FRAMES*SPEED === 1) {
        FRAMES = 0
        CYCLE += 1
        drawText()
    }

    // Draw the fern
    for (let i=0; i<ITERATIONS; i++) {
        // Choose a transformation
        let p = Math.random()
        let sum = 0
        for (let j=0; j<coefs.length; j++) {
            sum += coefs[j][6]
            if (p < sum) {
                // Perform tranformation on the coordinates
                coords = transform(coords, coefs[j])
                break
            }
        }

        // Dräw, bröther
        // Taking the opposite of the y coordinate so that the fern is not upside down
        // coefs[7] is a custom scaling factor
        ctx.beginPath()
        ctx.arc(coords[0]*ZOOM*coefs[0][7], -coords[1]*ZOOM*coefs[0][7], 1, 0, 2*Math.PI)
        ctx.fill()
    }

    // Request next
    FRAMES += 1
    NEXTFRAME = requestAnimationFrame(drawFern)
}


function transform(coords, coefs) {
    return [
        coefs[0]*coords[0] + coefs[1]*coords[1] + coefs[4],
        coefs[2]*coords[0] + coefs[3]*coords[1] + coefs[5]
    ]
}


function drawText() {
    let index = (CYCLE+1)%FERNS.length
    DOM.controls.current.innerHTML = FERNS[index].name
    DOM.controls.scaling.innerHTML = FERNS[index].coefs[0][7]
    let coefs = FERNS[index].coefs
    let matrix = 'a      b      c      d      f      e      p      <br>'
    for (let i=0; i<coefs.length; i++) {
        for (let j=0; j<coefs[i].length-1; j++) {
            if (coefs[i][j] >= 0) matrix += '+'
            matrix += coefs[i][j].toFixed(3) + ' '
        }
        matrix += '<br>'
        // matrix += `${coefs[i].join(' ')}<br>`
    }
    DOM.controls.matrix.innerHTML = matrix
}

//
// CONTROLS
//

DOM.controls.iterations.addEventListener('input', function() {
    let value = this.value
    value = Math.min(Math.max(this.min, value), this.max)
    this.value = value
    ITERATIONS = value
})

DOM.controls.pause.addEventListener('click', function() {
    if (RUNNING) {
        cancelAnimationFrame(NEXTFRAME)
        this.innerHTML = 'Play'
        RUNNING = false
    } else {
        NEXTFRAME = requestAnimationFrame(drawFern)
        this.innerHTML = 'Pause'
        RUNNING = true
    }
})

//
// INDEX
//

//
// Canvas setup
//
const canvas = DOM.canvas
const ctx = canvas.getContext('2d')

canvas.width = WIDTH
canvas.height = HEIGHT

// Center the canvas at the bottom center
ctx.translate(WIDTH*DWIDTH, HEIGHT*DHEIGHT)

ctx.fillStyle = '#218c74'

// Bop it
// Twist it
// Start it
let FRAMES = 0
let CYCLE = 0
let RUNNING = true
let NEXTFRAME = requestAnimationFrame(function() {
    drawFern()
    drawText()
})

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console