jquery - 如何使用 HTML5 canvas 创建软描边

标签 jquery html canvas drawing

我正在使用 HTML5 Canvas 创建绘图应用程序。

https://github.com/homanchou/sketchyPad

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

最佳答案

三种可能的解决方案:

  1. 您可以将线条写入屏幕外 Canvas ,应用模糊滤镜,然后将结果绘制到可见 Canvas 中。

  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(); }

通过减小宽度和增加 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(); }

关于jquery - 如何使用 HTML5 canvas 创建软描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010835/

相关文章:

javascript - .on ("change"的 jquery 语法,“input[name^=

html - Bootstrap 4 列没有正确响应

jquery - 如何将超链接添加到表格行 <tr>

javascript - 一种将 Canvas 中的 "toggle"图像当作 gif 的方法

Javascript HTML5 Canvas 绘制路径问题

jquery - 如何找到iOS应用程序的播放音​​频路径?

jquery - 循环回到迭代

javascript - 将 CSS 应用于禁用的按钮

jquery - CSS 3D 将 div 转换为 flex 的拱形

c# - 在单选按钮列表中选择选项时更改图像