我的问题是如何用 Canvas 创建进度条的背景,如下图:
我已经为它编写了代码,但我认为有更好的方法,例如我想知道我是否可以用一个 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/