Clément Andraud
Clément Andraud

Reputation: 9269

Javascript, HTML5 (canvas) progressbar with update

I'm looking for the best way to do a progress bar (in my case it's a life bar for a game) in an html5 canvas.

I don't know if it's better to use javascript and dom element, or draw this bar directly in the canvas.

I need an update function, for example myBar.updateValue(40), and I need to show the new bar without refresh all the page or all the canvas, of course.

Do you know something like that? An existing script? Thanks!

Upvotes: 1

Views: 3298

Answers (2)

Fredric Tillberg
Fredric Tillberg

Reputation: 56

HTML:

<div class='progress'>
    <div class='progress-bar' data-width='//Enter a percent value here'>
        <div class='progress-bar-text'>
            Progress: <span class='data-percent'>//This is auto-generated by the script</span>
        </div>
    </div>
</div>

CSS:

html, body {
    margin: 0;
    padding: 15px;
    width: 100%;
    height: 100%;
    position: relative;
    color: #fff;
}

.progress {
    position: relative;
    width: 100%;
    height: 30px;
}
.progress-bar {
    margin-bottom: 5px;
    width: 0%;
    height: 30px;
    position: relative;
    background-color: rgb(66, 139, 202);
}
.progress-bar-text {
    position: absolute;
    top: 0px;
    width: 100%;
    text-align: center;

    /*
    Do not change the values below,
    unless you want your text to display away from the bar itself. */
    line-height: 30px;
    vertical-align: middle;
}

jQuery:

$('.progress-bar').each(function (){    
    var datawidth = $(this).attr('data-width');

    $(this).find("span.data-percent").html(datawidth + "%");

    $(this).animate({
        width: datawidth + "%"
    }, 800);
});

Link to JSFiddle

The HTML data-width attribute is used to track the percent the bar should be set to. Change it to your liking.

The jQuery script works with ALL progress bars on your page (See the JSFiddle, so you don't have to copy and paste the same jQuery for every new progress bar. (Just be sure to keep the structure of the HTML, or change it to your liking).

The div "progress" is just an expander, it can be named whatever your want - without you having to change the jQuery.

EDIT: If you can use Javascript & HTML, don't use a canvas. Canvas (imho) are good for only 1 thing: Seat bookings for concerts, theaters and alike.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

It’s very easy in HTML/CSS:

<style>
    #progress-holder{width:400px;height:20px;background:grey}
    #progress{width:0;height:100%;background:black}
</style>
<div id="progress-holder">
    <div id="progress"></div>
</div>
<script>
    var progress = document.getElementById('progress');
    function updateValue(perc) {
        progress.style.width = perc+'%';
    }
    updateValue(40);
</script>

DEMO: http://jsbin.com/EGAzAZEK/1/edit

And animating with CSS: http://jsbin.com/EGAzAZEK/3/edit

Upvotes: 3

Related Questions