javascript - HTML5 Canvas 如何绘制带渐变边框的圆圈?

标签 javascript html html5-canvas bezier

在我搜索了很多之后,我找不到任何教程来回答如何在 HTML5 canvas 中绘制鼠形形状,请原谅我,因为我的数学很差。

不过我确实找到了一些相似/相关的答案,但我不知道如何结合这些知识...

HTML5 Canvas alpha transparency doesn't work in firefox for curves when window is big

Continuous gradient along a HTML5 canvas path

https://stackoverflow.com/a/44856925/3896501

我尝试达到的效果: enter image description here

感谢您的帮助!

更新 1:

到目前为止我创建的代码:

<body>
  <div class="con">
    <div class="ava"></div>
    <canvas id="canvas"></canvas>
  </div>
  <script>

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var shadowPadding = 8;
    var strokeWidth = 2;
    canvas.width = canvas.height = (64 + shadowPadding * 2) * window.devicePixelRatio
    canvas.style.width = canvas.style.height = `${canvas.width / window.devicePixelRatio}px`

    function drawMultiRadiantCircle(xc, yc, r, radientColors) {
        var partLength = (2 * Math.PI) / radientColors.length;
        var start = 0;
        var gradient = null;
        var startColor = null,
            endColor = null;

        for (var i = 0; i < radientColors.length; i++) {
            startColor = radientColors[i];
            endColor = radientColors[(i + 1) % radientColors.length];

            // x start / end of the next arc to draw
            var xStart = xc + Math.cos(start) * r;
            var xEnd = xc + Math.cos(start + partLength) * r;
            // y start / end of the next arc to draw
            var yStart = yc + Math.sin(start) * r;
            var yEnd = yc + Math.sin(start + partLength) * r;

            ctx.beginPath();

            gradient = ctx.createLinearGradient(xStart, yStart, xEnd, yEnd);
            gradient.addColorStop(0, startColor);
            gradient.addColorStop(1, endColor);

            ctx.lineWidth = strokeWidth;
            ctx.strokeStyle = gradient;

            // squircle START
            // https://stackoverflow.com/questions/50206406/drawing-a-squircle-shape-on-canvas-android
            // //Formula: (|x|)^3 + (|y|)^3 = radius^3
            // ctx.moveTo(-r, 0);
            // const radiusToPow = r ** 3;
            // const rad = r
            // for (let x = -rad ; x <= rad ; x++)
            //   ctx.lineTo(x + r, Math.cbrt(radiusToPow - Math.abs(x ** 3)) + r);
            // for (let x = rad ; x >= -rad ; x--)
            //   ctx.lineTo(x + r, -Math.cbrt(radiusToPow - Math.abs(x ** 3)) + r);
            // ctx.translate(r, r)
            // ctx.restore()
            // squircle END

            // circle START
            // https://stackoverflow.com/a/22231473/3896501
            ctx.arc(xc, yc, r, start, start + partLength);
            // circle END
            if (i === 1) {
              break
            }
            ctx.stroke();
            ctx.closePath();

            start += partLength;
        }
    }

    var someColors = [];
    someColors.push('#0F0');
    someColors.push('#0FF');
    someColors.push('#F00');
    someColors.push('#FF0');
    someColors.push('#F0F');

    var mid = canvas.width / 2;
    var r = (canvas.width - (shadowPadding * 2)) / 2 + (strokeWidth / 2)
    drawMultiRadiantCircle(mid, mid, r, someColors);

  </script>
  <style>
  .con {
    align-items: center;
    justify-content: center;
    display: flex;
    height: 4rem;
    margin: 6rem;
    width: 4rem;
    position: relative;
  }
  .ava {
    background: #555 50% no-repeat;
    background-size: contain;
    border-radius: 24px;
    height: 100%;
    width: 100%;
  }
  canvas {
    height: 100%;
    width: 100%;
    position: absolute;
  }
  </style>
</body>

用渐变颜色绘制圆的部分:

画一个圆圈:

我不知道如何像 context.arc 那样编写一个算法来绘制一部分 squircle。

最佳答案

如果我们阅读 wikipedia article on squircles ,我们看到这只是使用 2 或更高次方的未加权椭圆函数,这意味着我们可以很容易地计算给定“x”值的“y”值并以这种方式绘制东西,但这样做会给我们带来极不均匀的部分:x 中的小变化|将导致 y 发生巨大变化在起点和终点,以及 y 的微小变化在中点。

相反,让我们将 squircle 建模为参数函数,因此我们改变一个控制值并获得合理均匀间隔的间隔。我们可以在关于 superellipse function 的维基百科文章中找到这个解释。 :

x = |cos(t)^(2/n)| * sign(cos(t))
y = |sin(t)^(2/n)| * sign(sin(t))

t从 0 到 2π,半径固定为 1(因此它们从乘法中消失)。

如果我们实现它,那么我们几乎可以在事后添加彩虹色,分别绘制每个路径段,带有 strokeStyle使用 HSL 颜色的着色,其中色调值根据我们的 t 发生变化。值:

// alias some math functions so we don't need that "Math." all the time
const abs=Math.abs, sign=Math.sign, sin=Math.sin, cos=Math.cos, pow=Math.pow;

// N=2 YIELDS A CIRCLE, N>2 YIELDS A SQUIRCLE
const n = 4;

function coord(t) {
  let power = 2/n;
  let c = cos(t), x = pow(abs(c), power) * sign(c);
  let s = sin(t), y = pow(abs(s), power) * sign(s);
  return { x, y };
}

function drawSegmentTo(t) {
  let c = coord(t);
  let cx = dim + r * c.x;     // Here, dim is our canvas "radius",
  let cy = dim + r * c.y;     // and r is our circle radius, with
  ctx.lineTo(cx, cy);         // ctx being our canvas context.

  // stroke segment in rainbow colours
  let h = (360 * t)/TAU;
  ctx.strokeStyle = `hsl(${h}, 100%, 50%)`;
  ctx.stroke();  

  // start a new segment at the end point
  ctx.beginPath();
  ctx.moveTo(cx, cy);
}

然后我们可以将其与一些标准的 Canvas2D API 代码结合使用:

const PI = Math.PI,
      TAU = PI * 2,
      edge = 200, // SIZE OF THE CANVAS, IN PIXELS
      dim = edge/2,
      r = dim * 0.9,
      cvs = document.getElementById('draw');

// set up our canvas
cvs.height = cvs.width = edge;
ctx = cvs.getContext('2d');
ctx.lineWidth = 2;
ctx.fillStyle = '#004';
ctx.strokeStyle = 'black';
ctx.fillRect(0, 0, edge, edge);

完成所有设置后,绘制代码就非常简单了:

// THIS DETERMINES HOW SMOOTH OF A CURVE GETS DRAWN
const segments = 32;

// Peg our starting point, which we know is (r,0) away from the center.
ctx.beginPath();
ctx.moveTo(dim + r, dim)

// Then we generate all the line segments on the path
for (let step=TAU/segments, t=step; t<=TAU; t+=step) drawSegmentTo(t);

// And because IEEE floats are imprecise, the last segment may not
// actually reach our starting point. As such, make sure to draw it!
ctx.lineTo(dim + r, dim);
ctx.stroke();

运行它会产生以下 squircle:

a rainbox squircle of power 4

有了 jsbin,你就可以玩数字了:https://jsbin.com/haxeqamilo/edit?js,output

当然,您也可以采用完全不同的方式:使用 <path> 创建一个 SVG 元素(因为 SVG 是 HTML5 的一部分)元素并适当设置宽度,高度和 View 框,然后生成一个d属性和渐变颜色,但那绝对是way more finnicky .

关于javascript - HTML5 Canvas 如何绘制带渐变边框的圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676034/

相关文章:

javascript - 如何在 HTML Canvas 中添加淡出效果

jquery - 为特定的 div 设置 L_PREFER_CANVAS = true

javascript - 结合百分比与像素

javascript - 如何在 ace 编辑器中启用每个关键事件的自动完成功能?

javascript - 带有 ES6 Babel 的多个 package.jsons

javascript - 设置溢出的div或iframe的初始Y值?

javascript - 更改大小后 Canvas 状态丢失

html - RTL 中的星级评定系统

javascript - 如何在另一个 SVG 中插入内联 SVG 图像

java - 如何从多个图像中获取图像ID,以使用它来获取有关图像的完整数据并在单击图像时将其显示在不同页面上