gpt4 book ai didi

javascript - 性能方面——canvas vs base URI vs image

转载 作者:行者123 更新时间:2023-11-30 00:11:37 25 4
gpt4 key购买 nike

我正在创建一个色轮(选择器),我想知道显示色轮的最快最有效的方式。我目前正在使用 JavaScript 通过 Canvas 生成它。我认为其他选项是实际图像或数据 URI。如果有更快的方法,请告诉我。

显示颜色选择器最快最有效的方法是什么?

使用 JavaScript/canvas 的色轮

JSFiddle

var colorDisc = document.getElementById('surface'),
colorDiscRadius = colorDisc.offsetHeight / 2;

var drawDisk = function(ctx, coords, radius, steps, colorCallback) {
var x = coords[0] || coords, // coordinate on x-axis
y = coords[1] || coords, // coordinate on y-axis
a = radius[0] || radius, // radius on x-axis
b = radius[1] || radius, // radius on y-axis
angle = 360,
rotate = 0,
coef = Math.PI / 180;

ctx.save();
ctx.translate(x - a, y - b);
ctx.scale(a, b);

steps = (angle / steps) || 360;

for (; angle > 0; angle -= steps) {
ctx.beginPath();
if (steps !== 360) ctx.moveTo(1, 1); // stroke
ctx.arc(1, 1, 1, (angle - (steps / 2) - 1) * coef, (angle + (steps / 2) + 1) * coef);

if (colorCallback) {
colorCallback(ctx, angle);
} else {
ctx.fillStyle = 'black';
ctx.fill();
}
}
ctx.restore();
},
drawCircle = function(ctx, coords, radius, color, width) { // uses drawDisk
width = width || 1;
radius = [
(radius[0] || radius) - width / 2, (radius[1] || radius) - width / 2
];
drawDisk(ctx, coords, radius, 1, function(ctx, angle) {
ctx.restore();
ctx.lineWidth = width;
ctx.strokeStyle = color || '#000';
ctx.stroke();
});
};

if (colorDisc.getContext) {
drawDisk( // HSV color wheel with white center
colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2 - 1, colorDisc.height / 2 - 1],
360,
function(ctx, angle) {
var gradient = ctx.createRadialGradient(1, 1, 1, 1, 1, 0);
gradient.addColorStop(0, 'hsl(' + (360 - angle + 0) + ', 100%, 50%)');
gradient.addColorStop(1, "#FFFFFF");

ctx.fillStyle = gradient;
ctx.fill();
}
);
drawCircle( // gray border
colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2, colorDisc.height / 2],
'#555',
3
);
}
<canvas id="surface" width="500" height="500"></canvas>

最佳答案

我认为图像会更快,但如果不出现各种缩放伪像,则很难调整图像大小。所以我会选择 Canvas 。

但是,我认为还有第三种选择值得考虑:CSS 中的 Angular 渐变。这是使用现有功能执行此操作的方法:https://css-tricks.com/conical-gradients-css/

关于javascript - 性能方面——canvas vs base URI vs image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269701/

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