[英]Bounding box / bbox for a group after rotation in svg.js
使用 svg.js,我繪制了一個(游戲)板,它本質上是一組六邊形路徑。 添加所有六邊形后,我想將整個組旋轉 -60 度,然后讀出一個包含生成的(視覺)形狀的最小矩形框。
板子和盒子的外觀(紅色手繪)我要的:
但我不知道如何獲得紅框; 我所得到的似乎是藍色形狀周圍的框(這當然是整個組的 bbox,本身旋轉):
我發現的一些提示是使用外部組(依次包含收集字段的組); 旋轉內部組,並從外部組中獲取 bbox(); 不幸的是,這沒有任何改變。 或者,網絡上的一些來源建議改用 rbox() ,但這再次沒有改變,甚至不在 svg.js 3.0 的文檔中。
為了完整性,執行相關事情的代碼,即使這件事似乎是一個更普遍的問題。 我意識到我可以通過首先避免旋轉來規避這個問題,但我想找到一種解決方案,無需手動調整即可解決一系列類似的情況。
draw_board() {
let grp = this.canvas.group();
for (let field of this.fields) {
field.hex_display = grp.use(hexsym).size(this.w*this.hex_scale,this.h*this.hex_scale)
.center(field.cx,field.cy)
.addClass("hex_field")
.addClass(this.color);
}
let count = this.field.length;
let clipper = this.canvas.clip().path()
.M(...this.center(0,0))
.L(...this.center(0,count-1))
.L(...this.center(count-1,count-1))
.L(...this.center(count-1,0))
.Z();
grp.clipWith(clipper);
grp.rotate(-60);
let bb = grp.bbox();
this.canvas.viewbox(bb.x,bb.y,bb.w,bb.h)
}
任何指示如何解決這個問題?
這是一個擴展@RobertLongson 評論的示例。 紅色是getBoundingClientRect
,綠色是getBBox
。 我不確定兩者是否會為您解決問題。 使用getBoundingClientRect
需要計算 svg 相對於文檔的位置——這就是它偏移的原因。
var rotate = 0; function doRotation() { rotate += 10; if (rotate === 360) { rotate = 0; } var pathElement = document.querySelector('#path_1'); pathElement.setAttribute('transform', 'rotate(' + rotate + ' 40 40 )'); var groupElement = document.querySelector('#group_1'); var rectBBox = document.querySelector('#rect_1'); var rectBoundingClientRect = document.querySelector('#rect_2'); var bboxGroup = groupElement.getBBox(); rectBBox.setAttribute('x', bboxGroup.x); rectBBox.setAttribute('y', bboxGroup.y); rectBBox.setAttribute('width', bboxGroup.width); rectBBox.setAttribute('height', bboxGroup.height); var boundingClientRectGroup = groupElement.getBoundingClientRect(); rectBoundingClientRect.setAttribute('x', boundingClientRectGroup.x); rectBoundingClientRect.setAttribute('y', boundingClientRectGroup.y); rectBoundingClientRect.setAttribute('width', boundingClientRectGroup.width); rectBoundingClientRect.setAttribute('height', boundingClientRectGroup.height); } setInterval(doRotation, 100);
svg { overflow: visible }
<svg height="100px" viewBox="0 0 100 100"> <g id="group_1"> <path id="path_1" d="M35,25 L60,25 L50,50 L25,50 Z"></path> </g> <rect vector-effect="non-scaling-stroke" id="rect_1" stroke="#00ff00" stroke-width="1" fill="none"> </rect> <rect vector-effect="non-scaling-stroke" id="rect_2" stroke="#ff0000" stroke-width="1" fill="none"></rect> </svg>
使用 rbox。 就像grp.rbox(this.canvas)
一樣簡單
Rbox 基本上是一個圍繞 getBoundingClientRect 的包裝器。 但是,如果您傳入一個元素,則框將轉換為該元素的坐標系。 在您的情況下,您需要畫布坐標系統中的坐標。
如果您不帶參數調用 rbox,它將為您提供一個屏幕坐標框,並添加滾動(與 getBoundingClientRect 不同)
這是文檔的鏈接: https : //svgjs.dev/docs/3.0/manipulating/#rbox
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.