问答详情
源自:5-5 SVG-使用脚本控制路径文本

添加textpath成功后 text的宽高全部坍缩为0 请问大佬们,这个怎么解决

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>textPath</title>

</head>

<body>

<label>Path:</label>

<form>

<select id="text-path-select">

<option value="none">none</option>

<option value="#path1">path1</option>

<option value="#path2">path2</option>

<option value="#path3">path3</option>

</select>

</form>

<svg width="800" height="600"  xmlns="http://:wwww.w3.org/2000/svg">

<path id="path1" d="M 100  200 Q 200 100  300 200 T 500 200" stroke="rgb(0,255,0)" fill="none"></path>

<path id="path2" d="M100,300l100-50,200,100,100,-50 " stroke="rgb(255,0,0)" fill="none"></path>

<path id="path3" d="M100,400A400,300,0,0,0,500,400 " stroke="blue" fill="none"></path>

<text id="text" x="100" y="100" stroke="" fill="" font-size="20px" font-family="Microsoft YaHei">

Text path scripting <tspan id="tspan">动态使用路径文本</tspan>

</text>

</svg>

<script type="text/javascript">

// 命名空间

var SVG_NS = "http://:wwww.w3.org/2000/svg";

var XLINK_NS= "http://:wwww.w3.org/1999/xlink";

var select = document.getElementById('text-path-select');

var text = document.getElementById('text');

var tspan = document.getElementById('tspan');



function addTextPath() {

var textPath = document.createElementNS(SVG_NS,'textPath');

while(text.firstChild){

textPath.appendChild(text.firstChild);

}

text.appendChild(textPath);

}



function setTextPath(path) {

var textPath  = text.firstChild;  

textPath.setAttributeNS(XLINK_NS,'xlink:href',path);

var pathElment = document.querySelector(path);

tspan.setAttribute('fill',pathElment.getAttribute('stroke'));

}


function removeTextPath() {

var textPath = text.firstChild;

while(textPath.firstChild){

text.appendChild(textPath.firstChild);

}

text.removeChild(textPath);

tspan.removeAttribute('fill');

}



select.addEventListener("input",function () {

var value = select.value;

if (text.firstChild.tagName && text.firstChild.tagName.toLowerCase() == 'textpath') {

if (value == 'none') removeTextPath();

else setTextPath(value);

}else{

if (value != 'none') {

addTextPath();

setTextPath(value);

}

}

});

</script>

</body>

</html>


https://img1.mukewang.com/5b0a49dc0001e06c13490596.jpg



提问者:HakuPretty 2018-05-27 14:02

个回答

  • Luvoratorrrrry
    2018-10-22 23:17:50

    老哥。。你的坍缩这个词用的很是玄妙,你出现这种问题的原因其实很明显...

    你的namespace链接写错了,应该是'http://www.w3.org/2000/svg'而不是'http://:wwww.w3.org/2000/svg'.

    xlink的namespace也是,应该是'http://www.w3.org/1999/xlink'而不是'http://:wwww.w3.org/1999/xlink'