javascriptsliderhtml5-canvaslive-update

HTML5 Canvas Animation Slider


I am relatively new to Javascript so hopefully this will be a easy fix for a JS guru out there.

I am trying to create a animated html5 canvas, with simple white shapes floating down a page. My aim is to create sliders to control the size, shape, speed etc. of the white shapes floating down the page.

I have created the animation, and the slider, but am a bit stuck with how to get the value from the slider into the animation, and update the canvas to apply this new value as the user changes the slider.

To start off, I am trying to update the value of the slider into the speed value.

function sliderChange (value) {
    document.getElementById('sliderStatus').innerHTML = value;
}

var canvas = null;
var context = null;
var bufferCanvas = null;
var bufferCanvasCtx = null;
var flakeArray = [];
var flakeTimer = null;
var maxFlakes = 100;
var sliderSpeed = document.getElementById('sliderStatus')

function Flake() {
    this.x = Math.round(Math.random() * context.canvas.width);
    this.y = -10;
    this.drift = Math.random();
    this.speed = Math.round(Math.random() * sliderSpeed) + 5;
    this.width = (Math.random() * 3) + 2;
    this.height = (Math.random() * 3) + 100;
}

HTML body code:

<input type="range" min="0" max="100" value="50" step="2" onchange="sliderChange(this.value)"/>
<br /> <br />
Slider Value = <span id="sliderStatus">50</span>

Solution

  • Share the value from the slider handler method and set it directly on your sliderSpeed as well:

    function sliderChange (value) {
        document.getElementById('sliderStatus').innerHTML = value;
        sliderSpeed = +value;   // + will convert the string to number
    }
    
    ...
    var sliderSpeed = 50;       // same initial value as slider
    

    I would recommend: