如何使用HTML5画布创建柔和的笔触边缘

Hom*_*man 6 jquery html5 drawing canvas

我正在使用HTML5画布创建绘图应用程序.

https://github.com/homanchou/sketchyPad

我可以使用rgba来控制笔划中的不透明度,但是如何获得柔软的羽毛画笔边缘与硬圆形边缘?

Chr*_*use 7

三种可能的解决方

  1. 您可以将线条写入离屏画布,应用模糊滤镜,然后将结果绘制到可见画布中.

  2. 如果仅使用直线段,则可以对每个线段使用线性渐变.与线段的方向相比,梯度的方向必须是90"角.

  3. 在同一个地方多次绘制相同的线条.首先是全宽和低alpha.然后减小宽度并增加alpha.

为每个线段使用线性渐变的示例:

http://jsfiddle.net/chdh/MmYAt/

function drawSoftLine(x1, y1, x2, y2, lineWidth, r, g, b, a) {
   var lx = x2 - x1;
   var ly = y2 - y1;
   var lineLength = Math.sqrt(lx*lx + ly*ly);
   var wy = lx / lineLength * lineWidth;
   var wx = ly / lineLength * lineWidth;
   var gradient = ctx.createLinearGradient(x1-wx/2, y1+wy/2, x1+wx/2, y1-wy/2);
      // The gradient must be defined accross the line, 90° turned compared
      // to the line direction.
   gradient.addColorStop(0,    "rgba("+r+","+g+","+b+",0)");
   gradient.addColorStop(0.43, "rgba("+r+","+g+","+b+","+a+")");
   gradient.addColorStop(0.57, "rgba("+r+","+g+","+b+","+a+")");
   gradient.addColorStop(1,    "rgba("+r+","+g+","+b+",0)");
   ctx.save();
   ctx.beginPath();
   ctx.lineWidth = lineWidth;
   ctx.strokeStyle = gradient;
   ctx.moveTo(x1, y1);
   ctx.lineTo(x2, y2);
   ctx.stroke();
   ctx.restore(); }
Run Code Online (Sandbox Code Playgroud)

通过减小宽度和增加alpha来多次绘制线条的示例:

http://jsfiddle.net/chdh/RmtxL/

function drawSoftLine(x1, y1, x2, y2, lineWidth, r, g, b, a) {
   ctx.save();
   var widths = [1   , 0.8 , 0.6 , 0.4 , 0.2  ];
   var alphas = [0.2 , 0.4 , 0.6 , 0.8 , 1    ];
   var previousAlpha = 0;
   for (var pass = 0; pass < widths.length; pass++) {
      ctx.beginPath();
      ctx.lineWidth = lineWidth * widths[pass];
      var alpha = a * alphas[pass];
      // Formula: (1 - alpha) = (1 - deltaAlpha) * (1 - previousAlpha)
      var deltaAlpha = 1 - (1 - alpha) / (1 - previousAlpha)
      ctx.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + deltaAlpha + ")";
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
      previousAlpha = alpha; }
   ctx.restore(); }
Run Code Online (Sandbox Code Playgroud)


Nie*_*sol 1

我相当确定这取决于您使用的浏览器。最后我检查过(不久前 - 可能已经改变)Firefox 和 Chrome 没有抗锯齿边缘,而 IE9 则有。