Categories
canvas html image rotation

How to avoid image cutoff with rotate?

When you rotate an image using canvas, it’ll get cut off – how do I avoid this? I already made the canvas element bigger then the image, but it’s still cutting off the edges.

Example:

<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="https://www.faqcode4u.com/faq/411716/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>

Rotation always occur around the current origin. So you might want to use translate first to translate the canvas to the position around which you want to rotate (say the center) then rotate.

e.g.

ctx.translate(85, 85);
ctx.rotate(5 * Math.PI / 180);

The canvas now rotates around (85, 85).