性能方面-画布与基本URI与图像

Performance-wise - canvas vs base URI vs image

本文关键字:URI 图像 性能 -画 方面      更新时间:2023-09-26

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

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

使用JavaScript/画布的色轮

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>

我认为图像会更快,但如果不获得各种缩放伪影,则很难调整其大小。所以我会选择帆布。

然而,我认为还有第三个选项值得考虑:CSS中的角度梯度。以下是使用现有功能的方法:https://css-tricks.com/conical-gradients-css/