【发布时间】:2020-01-21 14:35:28
【问题描述】:
我目前正在 HTML5-Canvas 上构建一个小游戏。玩家控制一个矩形,矩形在其路径上画一条线。我正在存储矩形路径的坐标并从中创建一条线。问题是,矩形的坐标是它的左上角的位置。有什么方法可以绘制以坐标为中心的矩形?
【问题讨论】:
我目前正在 HTML5-Canvas 上构建一个小游戏。玩家控制一个矩形,矩形在其路径上画一条线。我正在存储矩形路径的坐标并从中创建一条线。问题是,矩形的坐标是它的左上角的位置。有什么方法可以绘制以坐标为中心的矩形?
【问题讨论】:
只需将新坐标传递给绘制矩形的函数即可:
newX = x - width / 2
newY = y - height / 2
示例:
function fillRectCentered(context, x, y, width, height) {
context.fillRect(x - width / 2, y - height / 2, width, height);
}
【讨论】:
如果有任何帮助,这是我来自 Game Maker 的代码。
///draw_rectangle(x,y,w,h,col,alpha,[rot])
/*
Draw rectangle from centre point.
*/
var px, py,
ox = argument[0], //centre point, pixels
oy = argument[1], //centre point, pixels
w = argument[2], //width, pixels
h = argument[3], //height, pixels
col = argument[4], //colour
alpha = argument[5],
a, b, c, ang,
rot = 0;
if (argument_count > 4) rot = argument[6];
draw_primitive_begin(pr_trianglestrip);
a = w/2;
b = h/2;
c = sqrt(sqr(a) + sqr(b))
ang = darctan(b/a);
px = ox + lengthdir_x(c, rot - ang);
py = oy + lengthdir_y(c, rot - ang);
draw_vertex_colour(px, py, col, alpha)
px = ox + lengthdir_x(c, rot + ang);
py = oy + lengthdir_y(c, rot + ang);
draw_vertex_colour(px, py, col, alpha)
px = ox + lengthdir_x(c, rot + ang + 180);
py = oy + lengthdir_y(c, rot + ang + 180);
draw_vertex_colour(px, py, col, alpha)
px = ox + lengthdir_x(c, rot - ang + 180);
py = oy + lengthdir_y(c, rot - ang + 180);
draw_vertex_colour(px, py, col, alpha)
draw_primitive_end();
【讨论】: