大型svg图像的处理技术

时间:2019-01-01 14:56:37

标签: html svg

我想让svg完全扩展到视口之外,因此不会将任何形状挤压在一起。然后,我将添加我知道该怎么做的平移和缩放。

但是我怎样才能让svg完全展开,以使所有形状都不会被挤压在一起,并且文本标签全部显示其文本而不会彼此重叠?

在我的示例中,svg仍在尝试将其所有内容放入svg视口中。我想让它在视口之外扩展,以使没有重叠,并使用缩放和平移来查看图像。

这些大图像是例外,而不是常态。

我创建了this jsfiddle来说明问题。

此刻,我的viewBox设置为:

<svg opacity="1" preserveAspectRatio="xMinYMin meet" viewBox="0 0 817 664" style="opacity: 1;">
  <!-- child nodes -->
</svg>

1 个答案:

答案 0 :(得分:1)

我认为这不仅仅是设计问题。 一种替代解决方案是使用某种方法来更改SVG的viewBox并旋转文本以避免重叠,或多或少都是这样。在这种情况下,我使用输入类型范围来更改viewBox,但是您可能决定选择其他解决方案。

const SVG_NS = 'http://www.w3.org/2000/svg';
const SVG_XLINK = "http://www.w3.org/1999/xlink";

let A = -1200;
let B = 1200;

let hexArray = []

function drawHexagon(r){  
  let points = "";
   for( let i = 1; i <= 6; i++ ){
        let a = i * ( Math.PI / 3 );
        let x = (r * Math.cos( a - Math.PI/2 )).toFixed(3);
        let y = (r * Math.sin( a  - Math.PI/2)).toFixed(3);
        points += `${x},${y} `;
      }
  return points;
}

function useHex(theParent,pos){
   let use = document.createElementNS(SVG_NS, 'use');
   use.setAttributeNS(SVG_XLINK, 'xlink:href', '#theHex');
   use.setAttributeNS(null,"x",pos.x);
   use.setAttributeNS(null,"y",pos.y);
   //use.setAttribute("title",'x value:'+pos.x);
   theParent.appendChild(use);
   hexArray.push(use);
  
   drawText('x value:'+pos.x,pos)
}

function drawText(val,pos){
  let txt = document.createElementNS(SVG_NS, 'text');
  txt.setAttributeNS(null,"x",pos.x);
  txt.setAttributeNS(null,"y",pos.y);
  txt.textContent = val;
  txt.setAttributeNS(null,"transform",`translate(0,30) rotate(-75  ${pos.x},${pos.y})`);
  textParent.appendChild(txt);
}

function connector(parent,p){
  let path = document.createElementNS(SVG_NS, 'path');
  let d =`M${p.x},${p.y}C${p.x},125 0,125 0,0`;
  path.setAttributeNS(null,"d",d);
  parent.appendChild(path);
}

for(let x = A; x <= B; x+=50){
  let pos = {x:x,y:250}
  useHex(useParent,pos);
  connector(connectors,pos);
}



itr.addEventListener("input",()=>{
svg.setAttributeNS(null, "viewBox", `${itr.value} -50 1200 550`); 
});
svg {
  border: 1px solid;
}
use {
  fill: white;
  stroke: #000;
}

#itr {
  width: 500px;
  display: block;
  margin: 2em auto;
}

#connectors path {
  fill: none;
  stroke: black;
}

#tooltip {
  position: absolute;
}

text {
  dominant-baseline: middle;
  text-anchor: end;
}
<input id="itr" type="range" min = "-1225" max = "25" value = "-600" />

<svg id="svg" viewBox="-600 -50 1200 550" style="--display:block;">
<defs><polygon  id="theHex"  points="21.651,-12.500 21.651,12.500 0.000,25.000 -21.651,12.500 -21.651,-12.500 -0.000,-25.000 "  ></polygon>
</defs> 
<g id="connectors">
  
</g>
<g id="useParent">
<use xlink:href="#theHex" y="0"  />
</g>
<g id="textParent">
  
</g>
</svg>