2013-12-18 42 views
1

我正在寻找在html5画布中执行进度条(在我的情况下,它是游戏的生命条)的最佳方式。Javascript,具有更新的HTML5(画布)进度条

我不知道是否最好使用javascript和dom元素,或者直接在画布上绘制这个条。

我需要更新功能,例如myBar.updateValue(40),当然,我需要显示新栏而不刷新所有页面或所有画布。

你知道吗?现有的脚本?谢谢!

+3

我假设你既然使用HTML5 Canvas进行游戏,你不关心那些吸吮的浏览器? (或换句话说,Internet Explorer) – srquinn

+0

[Bootstrap有一个CSS组件](http://getbootstrap.com/components/#progress)。 – undefined

+0

您是在画布上制作游戏,但卡在进度条上?! – David

回答

3

这是在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> 

DEMOhttp://jsbin.com/EGAzAZEK/1/edit

并与CSS动画:http://jsbin.com/EGAzAZEK/3/edit

+0

对于动画CSS转换可以是一个不错的选择。 – undefined

+0

我不喜欢使用settimeout,你有CSS的例子吗? –

+0

@ClémentAndraud当然,请参阅我的编辑:http://jsbin.com/EGAzAZEK/3/edit – David

0

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

的HTML data-width属性被用于跟踪百分比杆应设置为。改变它你喜欢。

jQuery脚本可以处理页面上的所有进度条(请参阅JSFiddle,因此,您不必为每个新的进度条复制和粘贴相同的jQuery (只要确保保持HTML,或将其更改为自己的喜好)

DIV的“进步”仅仅是一个扩展,它可以被命名为任何你想要 - 没有你不必更改jQuery的

编辑: 如果可以的话。使用Javascript & HTML,不要使用画布。画布(imho)只适用于一件事:为音乐会,剧院等提供座位预订。