gpt4 book ai didi

javascript - html5 Canvas 加载圆圈图像

转载 作者:太空狗 更新时间:2023-10-29 13:29:04 24 4
gpt4 key购买 nike

我正在尝试从 HTML5 canvas 中的图像创建一个加载圆。

这是我期望百分比为 50% 时的结果:

enter image description here

这是我经过大量测试后所做的:(蓝色笔画只是为了看到圆圈,之后它会被删除)

var img = new Image(); 
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
ctx.globalAlpha = 0.5
ctx.drawImage(img, 0, 0);
ctx.globalAlpha = 1;

var X = 50;
var Y = 50;
var Radius = img.width / 2;
var end = 40;
var start = 0;
var PI2 = Math.PI * 2;
var quart = Math.PI / 2;
var pct = 50 / 100;
var extent = (end - start) * pct;
var current = (end - start) / 100 * PI2 * pct - quart;

var pattern = ctx.createPattern(img, 'no-repeat');

ctx.beginPath();
ctx.arc(X, Y, Radius, -quart, current);
ctx.closePath();
ctx.fillStyle=pattern;
ctx.fill();
ctx.strokeStyle = "blue";
ctx.stroke();
}
<canvas></canvas>

如你所见,这里的结果并不异常(exception)

enter image description here

怎么了?

最佳答案

首先,您需要正确计算您的中心点:

var X = img.width / 2;
var Y = img.height / 2;

然后您需要沿着内半径Radius - 17 逆时针方向绕回:

ctx.beginPath();
ctx.arc(X, Y, Radius, -quart, current);
ctx.arc(X, Y, Radius - 17, current, -quart, true);
ctx.closePath();

如果你对笔划轮廓不感兴趣,可以先移动到中心,然后是arc:

ctx.beginPath();
ctx.moveTo(X, Y);
ctx.arc(X, Y, Radius, -quart, current);
ctx.closePath();

例子:

var img = new Image(); 
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
ctx.globalAlpha = 0.5
ctx.drawImage(img, 0, 0);
ctx.globalAlpha = 1;

var X = img.width / 2;
var Y = img.height / 2;
var Radius = img.width / 2;
var end = 40;
var start = 0;
var PI2 = Math.PI * 2;
var quart = Math.PI / 2;
var pct = 50 / 100;
var extent = (end - start) * pct;
var current = (end - start) / 100 * PI2 * pct - quart;

var pattern = ctx.createPattern(img, 'no-repeat');

ctx.beginPath();
ctx.moveTo(X, Y);
ctx.arc(X, Y, Radius, -quart, current);
ctx.closePath();
ctx.fillStyle = pattern;
ctx.fill();
}
<canvas></canvas>

关于javascript - html5 Canvas 加载圆圈图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com