是否可以在 Canvas 上倾斜图像以使其看起来像是另一幅图像的倒影?
这是一个例子:
我需要翻转和倾斜图像以获得所需的效果,但我无法让它看起来像那样。如何实现?
我找到了这个例子:
ctx.save();
ctx.transform(1,0,0.3,-1,0,0);
ctx.drawImage(tree1,74,-117,20,40);
ctx.restore();
他们似乎根据一些随机值设置变换。
但我无法理解它。这些值对我来说似乎很随机。我正在尝试创建一个动态函数,该函数允许我确定倾斜量并且适用于所有图像。
最佳答案
您可以使用 context.scale
垂直翻转图像:
// flip the canvas vertically
context.scale(1,-1);
以下是创建图像倾斜反射的步骤:
将 0,0 原点移动(move==translate)到所需的 x,y:
ctx.translate(x,y);
绘制原图image:
ctx.drawImage(img,0,0);
移动到原图底部:
ctx.translate(0,img.height);
缩放以垂直翻转图像:
ctx.scale(1,-1);
应用倾斜:
ctx.transform(1,0,skewAngle,1,0,0);
缩小反射图像(只是为了美观):
ctx.scale(1,0.50);
使反射图像的不透明度为 50%:
ctx.globalAlpha=0.50;
绘制反射图像:
ctx.drawImage(img,0,-img.height);
通过将所有转换设置为默认值来进行清理:
ctx.setTransform(1,0,0,1,0,0);
下面是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/character1.png";
function start(){
// 60x110
skewedReflection(img,25,25)
}
function skewedReflection(img,x,y){
// calc the 45 degree skew angle needed by ctx.transform
var skewAngle=-Math.tan(Math.PI/4);
// move the 0,0 origin to x,y
ctx.translate(x,y);
// draw the original image image
ctx.drawImage(img,0,0);
// move to the bottom of the original image
ctx.translate(0,img.height);
// use scale to flip the image
ctx.scale(1,-1);
// apply a skew
ctx.transform(1,0,skewAngle,1,0,0);
// shrink the reflected image
ctx.scale(1,0.50);
// make the reflected image 50% opacity
ctx.globalAlpha=0.50;
// draw the reflected image
ctx.drawImage(img,0,-img.height);
// clean up by setting all transforms to default
ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
关于Javascript Canvas 垂直倾斜图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33863042/