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

让人想犯罪 __ 提交于 2019-12-11 06:08:25

问题


I have an image with the following pattern:

I want to convert the straight lines in the image into a )|( shape. I have implemented C-type and S-type curves using canvas and its properties, but I am unable to do )|(-curve.

How can I do this?


回答1:


You could modify my previous answer slightly and have the halve sin range applied to the width (or height) as an offset, then take that offset x 2 and subtract from the total height of the new line.

What happens is that the sin() function will take an input and produce a new value between [0.0, 1.0]. Normally you would combine sin+cos to produce a circle, but we only need the value from one axis, and since we only need more of a ellipse shape we scale with a smaller value than radius (image size would represents diameter on the axis you're after).

So with the couple of modifications on the code I made in the other answer:

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>

(for vertical effect just reference where the changes are in the previous answer and apply offset instead of the formula).




回答2:


Use the distance from the horizontal center to apply a sin wave to the image scale. You only want part of the sin wave (PI/2 to PI) or (cos 0 to 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>


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

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