我目前正在HTML5-Canvas上构建一个小游戏。玩家控制一个矩形,矩形在其上绘制一条线。我正在存储矩形的坐标,并从中创建一条线。问题是,矩形的坐标是它左上角的位置。有没有办法用它的坐标中心绘制矩形?
答案 0 :(得分:0)
只需将新坐标传递给绘制矩形的函数:
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);
}
答案 1 :(得分:0)
如果有帮助,这是我来自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();