使用 jQuery 或 JavaScript 根据其他元素的可见性分配 SVG 坐标

问题描述 投票:0回答:1

我有 12 个圆形 div,由 4 个圆圈(A、B、C 和 D)的 3 条垂直线组成。 
Image 01

总共只有 6 个圆圈同时可见,并且每条垂直线上同时只有 2 个圆圈可见(1 个红色和 1 个绿色),例如像这样... 
Image 02

我想在这些圆圈后面放置一个蓝色的 SVG 形状,其坐标与可见圆圈的形状相匹配,如下所示: 
Image 03

这是我的静态蓝色形状的 SVG 代码:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 800 800" style="enable-background:new 0 0 800 800;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#88C9FF;}
</style>
<polygon class="st0" points="100,217.62 400,97.5 700,215.09 700,559.12 400,702.53 100,702.53 "/>
</svg>

有没有办法使 SVG 形状动态化,并根据圆圈的可见性输入形状点的 X 和 Y 坐标,最好使用 jQuery 或 JavaScript?

我正在思考以下内容:

如果“circle-1”可见,则插入“this”X 和 Y 坐标作为第一个 SVG 点,对于 6 个圆中的每个圆依此类推...

javascript jquery svg
1个回答
0
投票

您想在新绘制的点之间绘制多边形吗?

<svg-draw-board></svg-draw-board>
<style>
  svg-draw-board {
    width      : 100vw;
    height     : 180px;
    display    : inline-block;
    background : pink;
    cursor     : pointer;
  }
</style>
<script>
customElements.define('svg-draw-board', class extends HTMLElement {
  constructor() {
    let polygon=[];
    super()
       .attachShadow({mode:'open'})
       .innerHTML = `<svg width="100%" height="100%" viewBox="0 0 800 800"><polygon fill="blue"></polygon></svg>`;
    this.svg = this.shadowRoot.querySelector('svg');
    this.svg.onclick = (evt) => { // convert clientXY to SVG XY
      let CTM = this.svg.getScreenCTM();
      let x = (evt.clientX - CTM.e) / CTM.a;
      let y = (evt.clientY - CTM.f) / CTM.d;
      polygon.push([x,y]);
      this.drawCircle( x, y , evt.ctrlKey ? 50 : 30 );
      this.svg.querySelector("polygon").setAttribute("points", String(polygon.flat()) );
    };
  }
  drawCircle(cx, cy, r, fill = 'red') {
    this.svg.append( this.createSVGElement('circle', { cx, cy, r, fill }) );
  }
  createSVGElement( tag, attrs={} ) {
    const el = document.createElementNS('http://www.w3.org/2000/svg',tag);
    Object.entries(attrs).map(([name, val]) => el.setAttribute(name, val));
    return el;
  }
});
</script>

© www.soinside.com 2019 - 2024. All rights reserved.