gpt4 book ai didi

javascript - 将子项附加到 SVG 对象不会更新 Vue 中的 SVG

转载 作者:行者123 更新时间:2023-11-30 06:10:39 25 4
gpt4 key购买 nike

我有一个 SVG 对象,当我单击它时,我希望在那里出现一个矩形。我可以让它在 Vue 之外工作,但不能使用 Vue。

Vue 中的 HTML/模板字符串

<svg id="mysvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="1285 579 475 220" preserveAspectRatio="xMidYMid meet">
<image width="2111" height="1219" xlink:href="./hogviltsgatan.png"></image>
<g id="local" transform="scale(4)">
<rect x="50" y="50" width="100" height="100" rx="10" />
</g>

</svg>
<p id="coords">co-ordinates</p>

Vue 方法:

handleMouseClick(e) {
var
t = e.target,
x = e.clientX,
y = e.clientY,
target = (t == this.svg ? this.svg : t.parentNode),
svgP = this.svgPoint(target, x, y),
rect = this.createRect(this.NS, svgP.x ,svgP.y, 50, 50);
target.appendChild(rect);
}


svgPoint(element, x, y){
let pt = this.svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt.matrixTransform(element.getScreenCTM().inverse());
},

createRect (svg, x,y, height, width){
let rect = document.createElementNS(this.svg, 'rect');
rect.setAttributeNS(null, 'x', x);
rect.setAttributeNS(null, 'y', y);
rect.setAttributeNS(null, 'height', '75');
rect.setAttributeNS(null, 'width', '50');
// rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
return rect;
},

created() {

.
.
this.svg = document.getElementById('mysvg'),
this.NS = this.svg.getAttribute('xmlns'),
this.local = this.svg.getElementById('local'),
this.coords = document.getElementById('coords');
.
.

如果我将 target 打印到控制台,我可以看到矩形已被附加。但是,它没有出现在我的浏览器中。 svgPoint 和 createRect 方法有效。同样,该代码在 Vue 之外运行良好。看来 Vue 没有更新。如果我在模板字符串中硬编码一个矩形,它显示得很好。

最佳答案

使用 rects 的数据创建和操作对象数组

https://jsfiddle.net/53o2fxk6/2/

rects : [
{id: 'id1', x:10, y:10, w:20, h:20},
{id: 'id2', x:10, y:10, w:20, h:20},
{id: 'id3', x:10, y:10, w:20, h:20},
{id: 'id4', x:10, y:10, w:20, h:20}
]

操纵物体

createRect: function(_id, _x, _y, _w, _h) {
this.rects.push({id:_id, x:_x, y:_y, w:_w, h:_h});
}

使用 vue 方法创建 SVG

<svg>
<g v-for="rect in rects" :id="rect.id" />
<rect :x="rect.x" :y="rect.x" :width="rect.w" :height="rect.h">
</g>
</svg>

关于javascript - 将子项附加到 SVG 对象不会更新 Vue 中的 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com