HTML5画布 - 旋转对象而不移动坐标

34
我所拥有的是这个: Tank

我想要的是将红色矩形旋转20度,但最终结果出现了问题: Bad rotation

如您所见,矩形确实被旋转了,但它移动了位置,不再与黑色物体对齐。
我的代码是:
context.save();
context.rotate(angle * Math.PI / 180); // in the screenshot I used angle = 20
context.translate(angle * 4, 2);
context.fillStyle = "red";
context.fillRect(x + 14, y - 16, 5, 16);
context.restore();

我希望能让这个矩形旋转,但不改变它原来的位置。

谢谢。


苹果开发者文库关于画布和绕中心旋转的内容。这是一个带有示例代码的好资源。 - Goldfish Sandwich
3个回答

72

听起来你想要将矩形围绕它的中心点旋转。

红色矩形是原始的,黄色矩形是围绕中心点旋转的。

图片描述

为了做到这一点,在旋转之前需要使用context.translate移动至矩形的中心点。

// move the rotation point to the center of the rect

    ctx.translate( x+width/2, y+height/2 );

// rotate the rect

    ctx.rotate(degrees*Math.PI/180);

请注意,此时上下文已旋转。

这意味着绘制位置[ 0, 0 ] 在视觉上位于[ x+width/2, y+height/2 ]。

因此,您必须在[ -width/2, -height/2 ]处绘制旋转后的矩形(而不是在原始的未旋转的x / y处)。

// draw the rect on the transformed context
// Note: after transforming [0,0] is visually [-width/2, -height/2]
//       so the rect needs to be offset accordingly when drawn

    ctx.rect( -width/2, -height/2, width,height);

这里有一段代码以及一个 Fiddle:http://jsfiddle.net/m1erickson/z4p3n/

<!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; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var startX=50;
    var startY=80;

    // draw an unrotated reference rect
    ctx.beginPath();
    ctx.rect(startX,startY,100,20);
    ctx.fillStyle="blue";
    ctx.fill();

    // draw a rotated rect
    drawRotatedRect(startX,startY,100,20,45);

    function drawRotatedRect(x,y,width,height,degrees){

        // first save the untranslated/unrotated context
        ctx.save();

        ctx.beginPath();
        // move the rotation point to the center of the rect
        ctx.translate( x+width/2, y+height/2 );
        // rotate the rect
        ctx.rotate(degrees*Math.PI/180);

        // draw the rect on the transformed context
        // Note: after transforming [0,0] is visually [x,y]
        //       so the rect needs to be offset accordingly when drawn
        ctx.rect( -width/2, -height/2, width,height);

        ctx.fillStyle="gold";
        ctx.fill();

        // restore the context to its untranslated/unrotated state
        ctx.restore();

    }

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

不完全是这样:http://puu.sh/3gnZT.png 我需要它不要在中心点,因为这是一个“坦克”游戏(你要射击另一个坦克),这是你用来瞄准的“枪”,所以它必须固定在坦克(黑色物体)上。 - user2479365
8
@user2479365 MarkE提供了一个很好的、详细的答案,其中附有精美注释的代码。只需根据您的需求调整translate()函数即可。您可能希望使用-height而不是-height/2或类似的东西。 - Vedran Šego
1
你可能想要使用坦克中心的半径来偏移你的翻译。你可能还会发现使用转换矩阵更适合你的需求。 - Goldfish Sandwich
1
正如Vedran Šego和GoldfishSandwich在上面所说的那样,您只需要将旋转点调整为所需的枢轴点——translate(x,y+height/2)和rotate(0,-height/2,width,height)。 - markE
@markE 这是我自己编程问题的答案。谢谢。 - Sukima

12

你可以使用一个简单的函数来代替translate和rotate实现这个功能:

这个函数允许你从x和y开始绘制一条线,并以角度为长度结束:

function lineToAngle(ctx, x1, y1, length, angle) {

    angle *= Math.PI / 180;

    var x2 = x1 + length * Math.cos(angle),
        y2 = y1 + length * Math.sin(angle);

    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);

    return {x: x2, y: y2};
}

使用方法:

lineToAngle(ctx, x, y, length, angle);

演示

var canvas = document.querySelector('canvas'),
    ctx = canvas.getContext('2d'),
    x = 100, y =50, length = 40, angle = 0, dlt = -2;

(function animate() {
    
    //clear
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    ctx.beginPath();
    lineToAngle(ctx, x, y, length, angle);
    ctx.lineWidth = 10;
    ctx.stroke();

    angle += dlt;
    if (angle < -90 || angle > 0) dlt = -dlt;
    
    requestAnimationFrame(animate);
})();

function lineToAngle(ctx, x1, y1, length, angle) {

    angle *= Math.PI / 180;
    
    var x2 = x1 + length * Math.cos(angle),
        y2 = y1 + length * Math.sin(angle);
    
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);

    return {x: x2, y: y2};
}
body {background-color:#555557}
canvas {background:#ddd;border:1px solid #000}
<canvas></canvas>

enter image description here


0

对于矩形,您可以只画一条线。

在 HTML5 画布中,线条的绘制方式与矩形完全相同,因此可以使用此功能:

let canvas = document.getElementById('myCanvas')

let ctx = canvas.getContext('2d')

function drawRotatedRect(ctx, x, y, width, height, angle) {
  angle *= Math.PI / 180
  ctx.lineWidth = height / 2
  ctx.beginPath()
  ctx.moveTo(x, y)
  ctx.lineTo(x + width * Math.cos(angle), y + width * Math.sin(angle))
  ctx.stroke()
}


drawRotatedRect(ctx, 30, 30, 200, 100, 20)
canvas {
  border: 1px solid black;
  width: 100%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Rotated Rectangle</title>
</head>
<body>
  <canvas id='myCanvas'></canvas>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接