如何将图像像素转换为 )|( - canvas 中的曲线形状

How to convert image pixel into )|( -curve shape in canvas

我有一张具有以下图案的图像:

我想将图像中的直线转换为 )|( 形状。我已经使用 canvas 及其属性实现了 C 型和 S 型曲线,但我无法做到 ) |(-曲线。

我该怎么做?

使用距水平中心的距离对图像比例应用正弦波。您只想要部分正弦波(PI/2 到 PI)或(cos 0 到 PI/2)

var img = new Image;
img.src = "//i.stack.imgur.com/UvqUP.gif";
var ctx = can.getContext("2d");
img.onload = function () {
    var w,h,ch,cw,amount,x,scale;
    w = can.width = this.width;
    h = can.height = this.height;
    cw = w / 2;
    ch = h / 2;
    amount = 50;  // amount to bend in pixels
    amount *= 1 / ch;  // convert to unit scale
    for(var x = 0; x < w; x++) {
     scale = 1.0 - (Math.cos(((cw - x) / cw) * Math.PI * 0.5)) * amount;
        ctx.drawImage(this, x, 0, 1, h, x, ch - ch * scale , 1, h * scale); 
    }
}
<canvas id="can"></canvas>

您可以稍微修改 并将 sin 范围的一半作为偏移量应用于宽度(或高度),然后取该偏移量 x 2 并从新行的总高度中减去。

发生的事情是 sin() 函数将接受一个输入并产生一个介于 [0.0, 1.0] 之间的新值。通常你会组合 sin+cos 来产生一个圆,但我们只需要一个轴的值​​,因为我们只需要更多的椭圆形状,我们用比半径更小的值缩放(图像大小代表你轴上的直径)之后)。

因此,我对另一个答案中的代码进行了一些修改:

var ctx = c.getContext("2d");           // just some inits for demo
var img = new Image;
img.onload = slice;
img.src = "//i.stack.imgur.com/UvqUP.gif";

function slice() {
  var w = c.width = this.width;
  var h = c.height = this.height;
  var step = Math.PI / w;               // half circle / width of canvas
  var scale = 75;                       // max displacement on y
  
  for(var x = 0, offset; x < w; x++) {
    offset = Math.sin(step*x)*scale;
    ctx.drawImage(this,
      x, 0, 1, h,                       // source line from image
      x, offset, 1, h - offset*2);      // displaced line
  }
}
<canvas id=c></canvas>

(对于垂直效果,只需参考上一个答案中的更改位置并应用偏移量而不是公式)。