如何在画布中将图像像素转换为s曲线形状 [英] How to convert image pixel into s-curve shape in canvas
问题描述
我有这种类型的图像
我希望我们在图像中看到直线(实际上是像素),它应该转换成S曲线。我已经使用canvas及其属性实现了C型曲线,但无法进行S曲线。
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.
请帮助我。
推荐答案
如果我理解正确你想让每条垂直线跟随S?
If I understand you correctly you want each vertical line to follow a "S"?
如果是这种情况,你可以使用f.ex. Math.sin()
结合 drawImage()
及其裁剪参数,以切换每像素列的图像,同时取代基于sin()的切片。
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().
关键公式为:
var step = Math.PI * 2 / w;
这会将一个完整的圆圈映射到画布的宽度,这样当到达终点时我们将会是回到起点,在这种情况下形成一条S曲线。
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;
这将根据先前计算的步长值计算y轴上的位移,现在链接到x位置。这会产生介于-1和1之间的值,因此我们需要将其放大。比例表示像素数的最大半径。
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.
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>
在x轴上(显然在这种情况下不可见,因为沿着线条发生了变化,并且还有其他方法可以使用,例如在每一端都有一个s形状的过度绘图):
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>
这篇关于如何在画布中将图像像素转换为s曲线形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!