1
私は既にes5で書いたjQueryプラグインを作成しようとしていますが、今はTypeScriptにリファクタリングしたいと思います。JavaScriptで動的なSVG要素を作成しても、属性は無効です
私は<svg>
要素を作成しようとし、その後も<rect>
要素を作成し、<svg>
の<rect>
内部を追加した後、最終的にはDOMへ<svg>
を追加しています。
DOMのすべてがうまく見えますが、すべての要素と属性がありますが、何らかの理由でSVGがレンダリングされていません。
生成された要素をDOMからコピーし、それを静的要素としてindex.html
ファイル内にコピーすると、うまく描画されます。 (ここに見られるように)
TS:
// create the svg
let svgSquare = document.createElementNS('http://http://www.w3.org/2000/svg', 'svg');
const clickClass = clickAnimationName.length ? `shape-${shapeLayerNum}-click-${clickAnimationName}` : '';
const mouseEnterClass = mouseEnterAnimationName.length ? `shape-${shapeLayerNum}-mouse-enter-${mouseEnterAnimationName}` : '';
const mouseLeaveClass = mouseLeaveAnimationName.length ? `shape-${shapeLayerNum}-mouse-leave-${mouseLeaveAnimationName}` : '';
const svgSquareClasses = `${clickClass} ${mouseEnterClass} ${mouseLeaveClass}`;
// add svg classes
// svgSquare.setAttribute('class', svgSquareClasses);
// set svg attributes
svgSquare.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svgSquare.setAttribute('viewBox', `0 0 ${shapeScale/2} ${shapeScale/2}`);
svgSquare.setAttribute('fill', shapeConfig[`shape-${shapeLayerNum}-background`]);
svgSquare.setAttribute('stroke', 'black');
svgSquare.setAttribute('stroke-width', `${shapeScale/100}px`);
// sizing/centering
svgSquare.setAttribute('z-index', shapeConfig[`shape-${shapeLayerNum}-zIndex`]);
svgSquare.setAttribute('width', `${(shapeScale) + (shapeSpacing*2)}px`);
svgSquare.setAttribute('height', `${(shapeScale) + (shapeSpacing*2)}px`);
svgSquare.setAttribute('style', `margin-left: ${shapeMarginLeft}px; margin-top: ${shapeMarginTop}px;`);
// create the square rect
let polySquare = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
polySquare.setAttribute('width', `${(shapeWidth/2 - (shapeSpacing*2))}`);
polySquare.setAttribute('height', `${(shapeHeight/2) - (shapeSpacing*2)}`);
polySquare.setAttribute('x', `${shapeSpacing/2}`);
polySquare.setAttribute('y', `${shapeSpacing/2}`);
// rect polygon to svg
svgSquare.appendChild(polySquare);