我该如何旋转图片(例如旋转45度)并压缩图片。假设我有一个完美的正方形图像。我可以将其旋转到任何角度,但我想使旋转后的正方形被压缩,使得高度比宽度小2/3。由此产生的图像不会是一个完美的旋转正方形,而是一个被压扁的正方形。
您知道如何实现这个效果吗?
将正方形压缩非常容易,只需要应用一个比例:
ctx.scale(1, 2/3); // 将其压缩为纵向大小的2/3
不过需要通过 (相反的分数 * 高度) / 2
进行翻译以使其居中。
所以要旋转并压缩一个200x200像素的正方形图像,你只需要:
// rotation first
ctx.translate(100,100);
ctx.rotate(.3);
ctx.translate(-100,-100);
// than scale
ctx.translate(0,200 * (1/3) / 2) // move by half of the 1/3 space to center it
ctx.scale(1, 2/3); // squish it to 2/3 vertical size
ctx.drawImage(img, 0,0);
您可以使用2D画布通过扭曲宽度和高度来“伪造”3D效果
通过使用context.drawImage并且不按比例改变宽度和高度来实现此目的。
// draw image increasingly "squashed"
// to fake a 3d effect
ctx.drawImage(img,0,0,img.width,img.height,
left,
10,
(300-(right-left))/1,
300-(right-left)/1.5);
您可以调整扭曲比例以获得不同的效果,但它们都只是“压缩”。
这里有代码和一个 Fiddle:http://jsfiddle.net/m1erickson/J2WfS/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var left=1.0;
var right=300;
var sizing=.25;
var img=new Image();
img.onload=function(){
animate();
}
img.src="koolaidman.png";
function animate() {
// update scaling factors
left+=sizing;
right-=sizing;
if(left<0 || left>100){sizing = -sizing;}
console.log(left+"/"+right);
// clear and save the context
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
// draw image increasingly "squashed"
// to fake a 3d effect
ctx.drawImage(img,0,0,img.width,img.height,
left,
10,
(300-(right-left))/1,
300-(right-left)/1.5);
ctx.restore();
// request new frame
requestAnimFrame(function() {
animate();
});
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=235></canvas>
</body>
</html>