javascript - HTML SVG 复用组和
问题描述
所以我想重用一个分组的 svg 形状,并为每个实例单独更改组内元素之一的一个属性。下面的简化示例创建了第二个圆形,里面有一个矩形。我现在想使用 javascript 为每个形状单独更改“my-rect”矩形的“宽度”属性。使用 id "my-rect" 会改变两个矩形的宽度,但我只想改变一个。
我的目标(如果我的方法是无稽之谈):我必须绘制多个这些形状,唯一不同的是矩形的位置和宽度。
<svg height="1000" width="1000">
<a transform="translate(110,110)">
<g id="my-group">
<g>
<circle r="100" fill="#0000BF" stroke="black" stroke-width="2" fill-opacity="0.8"></circle>
</g>
<g>
<rect id="my-rect" y="-50" height="100" x="-50" width="50">
</rect>
</g>
</g>
</a>
<use xlink:href="#my-group" x="340" y="110"/>
</svg>
解决方案
肖恩 说:
如果 Web 组件自定义元素扩展为 SVG 命名空间,
则可以实现更复杂的重用
没错,您还不能制作自定义 SVG元素。
但是您可以制作一个生成SVG 的自定义元素:
customElements.define("rect-in-circle", class extends HTMLElement{
connectedCallback(){
const a = x => this.getAttribute(x);
this.innerHTML=`<svg viewBox="-100 -100 100 100">`+
`<g transform="translate(-50 -50)">`+
`<circle r="50" fill="#123456AB"/>`+
`<rect y="${a("y")}" height="${a("height")}"`+
`x="${a("x")}" width="${a("width" )}"/>`+
`</g></svg>`
}
});
svg{
width:100px;
height:100px;
background:grey;
fill:green;
}
<rect-in-circle x=-10 y=-10 width=20 height=20></rect-in-circle>
<rect-in-circle x=-40 y=-20 width=10 height=40></rect-in-circle>
<rect-in-circle x= 10 y= 20 width=30 height= 5></rect-in-circle>
SVG 的自定义元素是许多 oldskool SVG hack 的现代解决方案
更新
如果 OP 想要一个带圆圈的 SVG,我们可以使用 shadowDOM 以及不显示 lightDOM 中的元素这一事实。我们甚至可以使用未定义 <rect>
的元素(在 HTML 命名空间中),因此我们可以轻松地将它们注入到 SVG 字符串中。
<script>
customElements.define("rects-in-circles", class extends HTMLElement {
connectedCallback() {
setTimeout(() => {
const rects = [...this.children];
const width = rects.length * 100;
this.attachShadow({
mode: "open"
}).innerHTML = `<svg viewBox='0 0 ${width} 100'>` +
rects.map((rect, idx) => `<g transform='translate(${50+100*idx} 50)'>` +
`<circle r='50' fill='green'/>` +
rect.outerHTML +
`</g>`) + "</svg>";
})
}
});
</script>
<rects-in-circles>
<rect x=-10 y=-10 width=20 height=20></rect>
<rect x=-40 y=-20 width=10 height=40></rect>
<rect x=10 y=20 width=30 height=5></rect>
<rect x=-40 y=-40 width=50 height=50></rect>
</rects-in-circles>
(my)
相关 StackOverflow 答案:自定义元素和 SVG
推荐阅读
- javascript - 用css和jquery在圆圈中填充颜色的关键帧
- ajax - AJAX 发布到 Razor 页面中的处理函数
- java - 是否可以使用 Java 和 kotlin 来创建 Spring Boot 应用程序?
- html - 图片库过渡时的CSS淡入淡出
- python - 从 HTML 标签 Python/BeautifulSoup 获取第二个元素
- java - 在重复元素程序中遍历循环时出现 N 次问题
- apache - .htaccess 重定向适用于 .html 但不适用于使用 RewriteRule 的 .php
- git - Git 提交会忽略对某些子文件夹的更改。有关如何纠正问题的任何建议?
- javascript - AngularJS:当请求持续一分钟时,如何取消 block-ui 弹出窗口?
- splunk - 如何对数值变量进行直方图?