Tom*_*Tom 15 html5 canvas image rotation
使用画布旋转图像时,它会被切断 - 我该如何避免这种情况?我已经使画布元素比图像更大,但它仍然会切割边缘.
例:
<html>
<head>
<title>test</title>
<script type="text/javascript">
function startup() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'player.gif';
img.onload = function() {
ctx.rotate(5 * Math.PI / 180);
ctx.drawImage(img, 0, 0, 64, 120);
}
}
</script>
</head>
<body onload='startup();'>
<canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
小智 9
除了在旋转之前旋转画布外,您还需要在放置图像之前再次使用"翻译",如下所示:
ctx.translate(85, 85);
ctx.rotate(5 * Math.PI / 180); // for 5 degrees like the example from Vincent
Run Code Online (Sandbox Code Playgroud)
然后在添加图像之前再次使用translate
ctx.translate(-85, -85);
Run Code Online (Sandbox Code Playgroud)
这会将ctx.drawImage(img,0,0,10,10)的(0,0)坐标移回CANVAS的预期0,0坐标.
旋转始终发生在当前原点周围.因此,您可能希望首先使用translate将画布转换为您想要旋转的位置(比如中心)然后旋转.
例如
ctx.translate(85, 85);
ctx.rotate(5 * Math.PI / 180);
Run Code Online (Sandbox Code Playgroud)
画布现在旋转(85,85).