画布从底部中心图像角度旋转? [英] Canvas rotate from bottom center image angle?
问题描述
如何使用canvas html5元素从底部中心角旋转图片?
< 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.translate(185,185);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img,0,0,64,120);
}
}
< / script>
< / head>
< body onload ='startup();'>
< canvas id =canvasstyle =position:absolute; left:300px; top:300px; width =800height =800>< / canvas>
< / body>
< / html>不幸的是,这似乎是从图像的左上角旋转它。任何想法?
编辑:最后,对象(太空船)必须象时钟指针一样旋转,好像它向右/左转。
解决方案首先,你必须翻译到你想要旋转的点。在这种情况下,图片尺寸为64 x 120.要绕底部中心旋转,您要翻译为32,120。
ctx.translate(32,120);
这将带你到图片的底部中心。然后旋转画布:
ctx.rotate(90 * Math.PI / 180)
旋转90度。
然后,当你绘制图像时,尝试这样:
ctx.drawImage(img,-32,-120,64,120)
?这是否有效?
How do you rotate an image with the canvas html5 element from the bottom center angle?
<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.translate(185, 185);
ctx.rotate(90 * 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>
Unfortunately this seems to rotate it from the top left angle of the image. Any idea?
Edit: in the end the object (space ship) has to rotate like a clock pointer, as if it is turning right/left.
解决方案 First you have to translate to the point around which you would like to rotate. In this case the image dimensions are 64 x 120. To rotate around the bottom center you want to translate to 32, 120.
ctx.translate(32, 120);
That brings you to the bottom center of the image. Then rotate the canvas:
ctx.rotate(90 * Math.PI/180);
Which rotate by 90 degrees.
Then when you draw the image try this:
ctx.drawImage(img, -32, -120, 64, 120);
? Does that work?
这篇关于画布从底部中心图像角度旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!