How to convert image pixel into s-curve shape in canvas

后端 未结 1 920
迷失自我
迷失自我 2021-01-21 17:07

I have such type of image

I want that what we are seeing straight lines in image (actually which are pixel), it should get converted into the S-curve. I have implemente

相关标签:
1条回答
  • 2021-01-21 17:28

    If I understand you correctly you want each vertical line to follow a "S"?

    If that's the case you can use f.ex. Math.sin() combined with drawImage() and its clipping parameters to slice the image per pixel column while displacing the slice based on the sin().

    The key formulas are:

    var step = Math.PI * 2 / w;
    

    this maps a full circle to the width of the canvas so that when reaching the end we'll be back to the start point, in this case forming a S-curve.

    var y = Math.sin(step * x) * scale;
    

    This calculates the displacement on y-axis based on the previously calculated step value, now linked to x position. This produces a value between -1 and 1, so we need to scale it up. Scale represents maximum radius in number of pixels.

    Example

    snapshot

    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 * 2 / w;           // full circle / width of canvas
      var scale = 75;                       // max displacement on y
      
      for(var x = 0; x < w; x++) {
        ctx.drawImage(this,
          x, 0, 1, h,                       // source line from image
          x, Math.sin(step*x)*scale, 1, h); // displaced line
      }
    }
    <canvas id=c></canvas>

    On the x-axis (obviously not as visible in this case since the changes happens along the lines and there are other methods that could be used such as over-drawing with an s-shape at each end):

    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 * 2 / h;           // full circle / width of canvas
      var scale = 75;                       // max displacement on y
      
      for(var y = 0; y < h; y++) {
        ctx.drawImage(this,
          0, y, w, 1,                       // source line from image
          Math.sin(step*y)*scale, y, w, 1); // displaced line
      }
    }
    <canvas id=c></canvas>

    0 讨论(0)
提交回复
热议问题