You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RaphaelJS中获取矩形的中心坐标?

RaphaelJS矩形元素获取中心坐标的解决方法

RaphaelJS创建的矩形对象并没有内置的cx、cy属性,直接访问自然会返回undefined。要获取矩形中心坐标,需要通过矩形的位置和尺寸属性手动计算,步骤如下:

  • 先通过attr()方法获取矩形的x(左上角x坐标)、y(左上角y坐标)、width(宽度)、height(高度)属性
  • 中心坐标计算公式:
    • 水平中心 cx = x + width / 2
    • 垂直中心 cy = y + height / 2

代码示例

基础写法

// 假设rect是你已创建的矩形对象
var x = rect.attr("x");
var y = rect.attr("y");
var width = rect.attr("width");
var height = rect.attr("height");

var cx = x + width / 2;
var cy = y + height / 2;

console.info(cx);
console.info(cy);

简化写法(一次性获取多个属性)

var rectAttrs = rect.attr(["x", "y", "width", "height"]);
var cx = rectAttrs.x + rectAttrs.width / 2;
var cy = rectAttrs.y + rectAttrs.height / 2;

console.info(cx, cy);

扩展原型方法(方便重复使用)

如果需要频繁获取元素中心,可以给Raphael元素原型添加自定义方法:

// 扩展Raphael元素原型
Raphael.el.getCenter = function() {
  var attrs = this.attr(["x", "y", "width", "height"]);
  return {
    cx: attrs.x + attrs.width / 2,
    cy: attrs.y + attrs.height / 2
  };
};

// 使用时直接调用
var center = rect.getCenter();
console.info(center.cx, center.cy);

内容的提问来源于stack exchange,提问作者Sun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:19:58