0

这是我的代码:

//ct is a canvas context for drawing stuff
//bw is image width, bh is image height
function drawBox() {
    ct.translate(x, y)
    ct.rotate(rot)
    ct.drawImage(box, -bw/2, -bh/2)
    ct.fillRect((-bw/2) + (50 * Math.sin(rot)), (-bh/2) - (50 * Math.cos(rot)), 20, 20)
    ct.rotate(-rot)
    ct.translate(-x, -y)
}

它应该画出方框,然后将矩形放在它前面 50 像素处。但是,它不起作用。每次图像旋转一次,矩形都会围绕图像旋转两次。

我做了一些实验,这段代码有效:

function drawBox() {
    ct.drawImage(box, x, y)
    ct.fillRect((x) + (50 * Math.sin(rot)), (y) - (50 * Math.cos(rot)), 20, 20)
}

我已移除旋转并将坐标更改为xand y。如果上面的代码有效,为什么不旋转它然后执行此代码?我该如何解决这个问题?

4

1 回答 1

0

我似乎已经解决了这个问题。我意识到问题是我在绘制另一个盒子时围绕错误的点旋转,所以我使用了这段代码:

function drawBox() {
    ct.translate(x, y)
    ct.rotate(rot)
    ct.drawImage(box, -halfbw, -halfbh)
    ct.rotate(-rot)
    ct.translate(-x, -y)
    if (sCount > 0) {
        sCount --
        ct.translate(x, y+halfbh)
        ct.rotate(rot+PI)
        ct.fillRect((halfbh * Math.sin(rot)), (halfbh * Math.cos(rot))+halfbh, 10, 50)
        ct.rotate(-rot-PI)
        ct.translate(-x, -y-halfbh)
    }
}

(我添加了一些不相关的东西,比如sCount,但这本质上就是问题所在。)我不得不取消翻译和取消旋转,这样我才能重新翻译并旋转到第二个框在正确位置的位置.

于 2013-03-06T13:55:51.583 回答