【问题标题】:Draw rectangle with it's center at coordinates以坐标为中心绘制矩形
【发布时间】:2020-01-21 14:35:28
【问题描述】:

我目前正在 HTML5-Canvas 上构建一个小游戏。玩家控制一个矩形,矩形在其路径上画一条线。我正在存储矩形路径的坐标并从中创建一条线。问题是,矩形的坐标是它的左上角的位置。有什么方法可以绘制以坐标为中心的矩形?

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    只需将新坐标传递给绘制矩形的函数即可:

    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);
    }
    

    【讨论】:

    • 哇,这很容易!谢谢你!我不知道fillRect函数,我调用了rect(),然后调用了fil()
    【解决方案2】:

    如果有任何帮助,这是我来自 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      相关资源
      最近更新 更多