如何在 JavaScript 中确定图像旋转后是否位于可见画布之外?
我正在编写一款基于画布的游戏,其中一次涉及画布上的许多精灵。在某些情况下,精灵不可见,为了节省渲染周期,如果玩家看不到它们,我不会将它们渲染到画布上。这对于不旋转的精灵非常有用,但一旦它们旋转(尤其是矩形),我就无法再准确地确定它们是否仍在可见画布内。
这是我到目前为止作为主渲染循环的一部分所做的事情:
if (image !== null) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation * Math.PI/180);
ctx.drawImage(image, 0,0, this.width, this.height);
ctx.restore();
}
在使用上面的代码渲染精灵之前,我使用以下代码确定它是否可见:
// Only draw sprite sthat are visible to the player.
if (sprite.x + boundingBox >= 0 && sprite.y + boundingBox >= 0 && sprite.x <= this.width && sprite.y <= this.height) {
sprite.draw(this.gameConsole.ctx);
}
发生的情况是,一旦我旋转一个不均匀的精灵,例如一个矩形,宽度和高度不再正确,因为它们假设它们处于非旋转状态。您将如何解决这个问题?
I am writing a canvas-based game which involves many sprites on the canvas at one time. In some cases the sprites are not visible and to save render cycles I do not render them to the canvas if the player will not see them. This works great for sprites that are not rotated but as soon as they become rotated (especially rectangles) I can no longer accurately determine if they are still within the visible canvas.
Here is what I am doing so far as part of my main render loop:
if (image !== null) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation * Math.PI/180);
ctx.drawImage(image, 0,0, this.width, this.height);
ctx.restore();
}
Before I render the sprite using the above code I determine if it is visible using this code:
// Only draw sprite sthat are visible to the player.
if (sprite.x + boundingBox >= 0 && sprite.y + boundingBox >= 0 && sprite.x <= this.width && sprite.y <= this.height) {
sprite.draw(this.gameConsole.ctx);
}
What happens is that once I rotate a nonuniform sprite for example a rectangle the width and height are no longer correct because they assume they are in an nonrotated state. How would you approach this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
旋转表示,其中点 P 是非均匀精灵的角点(4 个之一),在
旋转矩阵的帮助
下旋转后会产生 R,因此您可以测试 R 是否在画布内。
如果您使用 ctx.setTransform 而不是旋转,您可以一次完成所有操作,即首先测试,如果需要则渲染;)
the rotation says that where point P is a corner-point (one of the 4) of the nonuniform sprite resulting in R after Rotation
with the help of a rotation matrix
so you could test if R is inside the canvas.
if you use ctx.setTransform instead of rotate you can do it all at once, that is test first, render if needed ;)
您可以计算对角线并用它来确定精灵是否可见
You could calculate the diagonal and use that to determine whether the sprite is visible