【问题标题】:Javascript, HTML5 (canvas) progressbar with update带有更新的 Javascript、HTML5(画布)进度条
【发布时间】:2013-12-20 04:04:24
【问题描述】:

我正在寻找在 html5 画布中制作进度条(在我的情况下是游戏的生命条)的最佳方式。

不知道是用javascript和dom元素比较好,还是直接在canvas里画这个bar。

我需要一个更新功能,例如myBar.updateValue(40),当然我需要在不刷新所有页面或所有画布的情况下显示新栏。

你知道类似的事情吗?现有的脚本?谢谢!

【问题讨论】:

标签: javascript jquery canvas progress-bar


【解决方案1】:

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

演示http://jsbin.com/EGAzAZEK/1/edit

并使用 CSS 制作动画:http://jsbin.com/EGAzAZEK/3/edit

【讨论】:

  • 我不喜欢使用 settimeout,你有 CSS 的例子吗?
  • 我应该添加这不是 HTML5 画布方法.... 除非您打算在画布顶部使用 position:absolute 和 z-index 来创建其在画布中的效果,否则你需要使用fillrect
【解决方案2】:

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 "progress" 只是一个扩展器,它可以任意命名 - 无需更改 jQuery。

编辑: 如果您可以使用 Javascript 和 HTML,请不要使用画布。帆布(恕我直言)仅适用于一件事:音乐会、剧院等的座位预订。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多