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

不打扰是莪最后的温柔 提交于 2019-12-02 05:45:05

问题


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 implemented C-type of curve using canvas and its properties, but unable to do S-curve.

Please help me for this.


回答1:


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

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>


来源:https://stackoverflow.com/questions/42712312/how-to-convert-image-pixel-into-s-curve-shape-in-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!