HTML5 Canvas如何绘制带有渐变边框的鼠形?

时间:2019-06-19 21:21:50

标签: javascript html html5-canvas bezier

经过大量的搜索,我找不到任何回答如何在HTML5画布中绘制波浪形的教程,请原谅我,因为我的数学知识很差。

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

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一样编写一种算法,该算法可以绘制一部分鼠尾草。

2 个答案:

答案 0 :(得分:5)

如果我们阅读wikipedia article on squircles,我们会发现这只是2或更高次方的未加权椭圆函数,这意味着我们可以很容易地计算给定“ x”值的“ y”值并绘制图形这样,但这样做会给我们带来极为不平衡的细分:x的微小变化将导致y的起点和终点发生巨大变化,而y的微小变化将导致中点。

相反,让我们将鞘管建模为参数函数,以便我们改变一个控制值并获得合理平均间隔的间隔以供使用。我们可以在superellipse function上的维基百科文章中找到对此的解释:

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

t的范围是从0到2π,并且半径固定为1(因此它们从乘法运算中消失了)。

如果我们实现了这一点,那么我们几乎可以将彩虹着色作为事后考虑,分别绘制每个路径段,并使用strokeStyle着色,该着色使用HSL颜色,其中色相值根据{{1} }值:

t

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

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

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

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

运行此命令会产生以下问题:

a rainbox squircle of power 4

使用jsbin,您可以使用以下数字:https://jsbin.com/haxeqamilo/edit?js,output

当然,您也可以采用另一种方法:使用// 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(); 元素创建SVG元素(因为SVG是HTML5的一部分),并适当设置宽度,高度和视图框,然后生成{ {1}}属性和渐变颜色,但这绝对是way more finnicky

答案 1 :(得分:4)

通过手头的数学表达式,您可以对边界矩形进行全面扫描,并逐像素评估

  • 它在外面
  • 它是边界的一部分
  • 它位于里面

对于渐变,我将一些连续函数应用于角度。就像一些罪恶/ cos的东西一样:

let ctx=cnv.getContext("2d");

function gradient(angle){
  return "rgb("+
    (128+127*Math.sin(angle*8))+","+
    (128+127*Math.cos(angle*6))+","+
    (128+127*Math.sin(angle*16))+")";
}

for(let x=0;x<360;x++){
  ctx.fillStyle=gradient(x*Math.PI/180);
  ctx.fillRect(250-180+x,0,1,10);
}

let mx=250,my=90,rx=70,ry=70;

let start=Date.now();

for(let x=-rx;x<=rx;x++)
  for(let y=-ry;y<=ry;y++){
    let r4=Math.pow(x/rx,4)+Math.pow(y/ry,4);
    if(r4<0.8){
      ctx.fillStyle="gray";
      ctx.fillRect(mx+x,my+y,1,1);
    }else if(r4<1){
      ctx.fillStyle=gradient(Math.atan2(x,y));
      ctx.fillRect(mx+x,my+y,1,1);
    }
  }

console.log(Date.now()-start);
<canvas id="cnv" width="500" height="170"></canvas>

对于现实生活中的使用,这种方法在屏幕外合成ImageData并可能预先计算梯度的情况下也可能会更好:

let ctx=cnv.getContext("2d");

let gradient=new Uint8Array(360*3);

for(let x=0;x<360;x++){
  let r=gradient[x*3]=128+127*Math.sin(x*Math.PI/180*8);
  let g=gradient[x*3+1]=128+127*Math.cos(x*Math.PI/180*6);
  let b=gradient[x*3+2]=128+127*Math.sin(x*Math.PI/180*16);
  ctx.fillStyle="rgb("+r+","+g+","+b+")";
  ctx.fillRect(250-180+x,0,1,10);
}

let mx=250,my=90,rx=70,ry=70;

let start=Date.now();

let imgdata=ctx.createImageData(rx*2+1,ry*2+1);
let data=imgdata.data;

for(let y=-ry,idx=0;y<=ry;y++)
  for(let x=-rx;x<=rx;x++){
    let r4=Math.pow(x/rx,4)+Math.pow(y/ry,4);
    if(r4<0.8){
      data[idx++]=128;
      data[idx++]=128;
      data[idx++]=128;
      data[idx++]=255;
    }else if(r4<1){
      gidx=Math.floor(180+Math.atan2(x,y)*180/Math.PI)%360*3;
      data[idx++]=gradient[gidx++];
      data[idx++]=gradient[gidx++];
      data[idx++]=gradient[gidx++];
      data[idx++]=255;
    }else idx+=4;
  }

ctx.putImageData(imgdata,mx-rx,my-ry);

console.log(Date.now()-start);
<canvas id="cnv" width="500" height="170"></canvas>

在我的机器上,后一种变体在第一次运行时速度较慢(大约40毫秒对35毫秒),但在随后的变体中却显着更快(14毫秒对31毫秒,因此另一个速度并没有真正加快)。但是我尚未检查是否是ImageDatagradient[]或两者的结果。


编辑06-07-2019 ,但不同时应用建议...

Uint32Array使它更短,更简单和更快:

let ctx=cnv.getContext("2d");

let gradient=new Uint32Array(360);

for(let x=0;x<360;x++){
  let r=128+127*Math.sin(x*Math.PI/180*8);
  let g=128+127*Math.cos(x*Math.PI/180*6);
  let b=128+127*Math.sin(x*Math.PI/180*16);
  gradient[x]=0xFF000000+(b<<16)+(g<<8)+r;
  ctx.fillStyle="rgb("+r+","+g+","+b+")";
  ctx.fillRect(250-180+x,0,1,10);
}

let mx=250,my=90,rx=70,ry=70;

let start=Date.now();

let imgdata=ctx.createImageData(rx*2+1,ry*2+1);
let data=new Uint32Array(imgdata.data.buffer);

for(let y=-ry,idx=0;y<=ry;y++)
  for(let x=-rx;x<=rx;x++,idx++){
    let r4=Math.pow(x/rx,4)+Math.pow(y/ry,4);
    if(r4<0.8){
      data[idx]=0xFF808080;
    }else if(r4<1){
      gidx=Math.floor(180+Math.atan2(x,y)*180/Math.PI)%360;
      data[idx]=gradient[gidx];
    }
  }

ctx.putImageData(imgdata,mx-rx,my-ry);

console.log(Date.now()-start);
<canvas id="cnv" width="500" height="170"></canvas>

但是对于32位数字来说,抗锯齿并不是很简单,因此这一部分恢复为单独的组件:

let ctx=cnv.getContext("2d");

let gradient=new Uint8Array(360*3);

for(let x=0;x<360;x++){
  let r=gradient[x*3]=128+127*Math.sin(x*Math.PI/180*8);
  let g=gradient[x*3+1]=128+127*Math.cos(x*Math.PI/180*6);
  let b=gradient[x*3+2]=128+127*Math.sin(x*Math.PI/180*16);
  ctx.fillStyle="rgb("+r+","+g+","+b+")";
  ctx.fillRect(250-180+x,0,1,10);
}

let mx=250,my=90,r=70,rr=65;

let start=Date.now();

let imgdata=ctx.createImageData(r*2+1,r*2+1);
let data=imgdata.data;

function mix(a,b,w){
  return b+(a-b)*w;
}

for(let y=-r,idx=0;y<=r;y++)
  for(let x=-r;x<=r;x++){
    let d=Math.pow(Math.pow(x,4)+Math.pow(y,4),0.25);
    if(d<=rr){
      data[idx++]=128;
      data[idx++]=128;
      data[idx++]=128;
      data[idx++]=255;
    }else if(d>=r){
      idx+=4;
    }else{
      let gidx=Math.floor(180+Math.atan2(x,y)*180/Math.PI)%360*3;
      if(d<rr+1){
        let w=d-rr;
        data[idx++]=mix(gradient[gidx++],128,w);
        data[idx++]=mix(gradient[gidx++],128,w);
        data[idx++]=mix(gradient[gidx++],128,w);
        data[idx++]=255;
      }else if(d>r-1){
        let w=r-d;
        data[idx++]=mix(gradient[gidx++],255,w);
        data[idx++]=mix(gradient[gidx++],255,w);
        data[idx++]=mix(gradient[gidx++],255,w);
        data[idx++]=255;
      }else{
        data[idx++]=gradient[gidx++];
        data[idx++]=gradient[gidx++];
        data[idx++]=gradient[gidx++];
        data[idx++]=255;
      }
    }
  }

ctx.putImageData(imgdata,mx-r,my-r);

console.log(Date.now()-start);
<canvas id="cnv" width="500" height="170"></canvas>