性能方面 - 画布与基础URI对比图像

时间:2016-03-28 19:34:17

标签: javascript image performance canvas base-url

我正在创建一个色轮(拾取器),我想知道最快最有效的显示色轮的方法。我目前正在使用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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我认为图像会更快,但如果没有获得各种缩放工件,就很难调整图像大小。所以我会选择画布。

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