一、引用js文件
<script src = "d3.js"></script> <script src="MultiText.js" charset="utf-8"></script>或者
<pre name="code" class="javascript"><script src = "d3.js"></script><script src="http://www.ourd3js.com/library/multext.js" charset="utf-8"></script> 二、函数的参数
文件里实现了一个appendMultiText()函数,其个参数的意义为:
appendMultiText( container, //文本的容器,可以是<svg>或<g> str, //字符串 posX, //文本的x坐标 posY, //文本的y坐标 width, //每一行的宽度,单位为像素 fontsize, //文字的大小(可省略),默认为 14 fontfamily //文字的字体(可省略),默认为 simsun, arial )三、添加多行文本
var width = 400, height = 400; var str= "青青子衿,悠悠我心,但为君故,沉吟至今。"; var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height) var multi = appendMultiText(svg,str,30,100,120,20,"simsun");若要使文本旋转,则添加如下代码即可:
multi.attr("transform","rotate(-20)")
运行结果如下:
MultiText.js代码如下:
/** * Created by Silence_C on 2016/5/13. */ function appendMultiText(container, str, posX, posY, width, fontsize, fontfamily){ if( arguments.length < 6){ fontsize = 14; } if( arguments.length < 7){ fontfamily = "simsun, arial"; } //鑾峰彇鍒嗗壊鍚庣殑瀛楃涓� var strs = splitByLine(str,width,fontsize); var mulText = container.append("text") .attr("x",posX) .attr("y",posY) .style("font-size",fontsize) .style("font-family",fontfamily); mulText.selectAll("tspan") .data(strs) .enter() .append("tspan") .attr("x",mulText.attr("x")) .attr("dy","1em") .text(function(d){ return d; }); return mulText; function splitByLine(str,max,fontsize){ var curLen = 0; var result = []; var start = 0, end = 0; for(var i=0;i<str.length;i++){ var code = str.charCodeAt(i); var pixelLen = code > 255 ? fontsize : fontsize/2; curLen += pixelLen; if(curLen > max){ end = i; result.push(str.substring(start,end)); start = i; curLen = pixelLen; } if( i === str.length - 1 ){ end = i; result.push(str.substring(start,end+1)); } } return result; } }