javascript - 背景进度条 Canvas

标签 javascript jquery html css canvas

我的问题是如何用 Canvas 创建进度条的背景,如下图:

enter image description here

我已经为它编写了代码,但我认为有更好的方法,例如我想知道我是否可以用一个 Canvas 来完成这段代码:

$(document).ready(function () {
    var canvasAnimation = document.getElementById("animation");
    var ctxAnimation = canvasAnimation.getContext("2d");
    ctxAnimation.beginPath();
    ctxAnimation.arc(75, 75, 65, 0, 2 * Math.PI);
    ctxAnimation.lineWidth = 10;
    ctxAnimation.strokeStyle = "#F3F3F3";
    ctxAnimation.stroke();

    var canvasBackground = document.getElementById("background");
    var ctxBackground = canvasAnimation.getContext("2d");
    ctxBackground.beginPath();
    ctxBackground.arc(75, 75, 65, 1.2, 2 * Math.PI);
    ctxBackground.lineWidth = 10;
    ctxBackground.strokeStyle = "#1ABC9C";
    ctxBackground.stroke();
})
.my-container{
                position:relative;
                width:150px;
                height:150px;
                margin:50px auto;
            }
            canvas{
                position:absolute;
                top:0;
                left:0;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
    <canvas id="background" width="150" height="150"></canvas>
    <canvas id="animation" width="150" height="150"></canvas>
</div>

第二个问题:

第二个问题是我想让我的笔画像上图一样有border-radius

最佳答案

这绝对有可能使用单个 Canvas 。您只需要删除第二个 Canvas 及其上下文,并将对 ctxBackground 的任何引用替换为 ctxAnimation。这是可行的,因为 Canvas API 和 SVG 一样,使用 painter's rendering model :

Paint is applied in successive operations to the output device such that each operation paints over some area of the output device. When the area overlaps a previously painted area the new paint partially or completely obscures the old.

在您的示例中,如果我们先绘制浅灰色圆圈,然后绘制蓝绿色线,则蓝绿色线将绘制在圆上。通过应用这种技术,我们得到以下代码:

const canvas = document.getElementById("animation");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(75, 75, 65, 0, 2 * Math.PI);
ctx.lineWidth = 10;
ctx.strokeStyle = "#F3F3F3";
ctx.stroke();

ctx.beginPath();
ctx.arc(75, 75, 65, 1.2, 2 * Math.PI);
ctx.lineWidth = 10;
ctx.strokeStyle = "#1ABC9C";
ctx.stroke();

至于启用“边框半径”效果,您可以将 lineCap 属性设置为圆形:ctx.lineCap = "round";

Here's a fiddle of the final code.

您可能想查看一些 Canvas 文档 here.

关于javascript - 背景进度条 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631117/

相关文章:

javascript - 在添加到文档之前,Javascript/jQuery DOM 创建是否安全?

javascript - 使用行和列索引更改 TD 内的输入值

jquery - 使用 jQuery 和 CSS、HTML 创建行号等文本编辑器

java - 如何在 th :if tag using thymeleaf 中有多个条件

javascript - Javascript 分析脚本是否容易受到简单的数据黑客攻击?

javascript - 在函数外部声明变量

javascript - 是否可以一次绑定(bind)多种类型的数据?

html - Codeigniter 中的 PHP 回显位置

php - undefined index html 选择

javascript - 反复缩小一个div的宽度