作业帮 > 综合 > 作业

求用javascript+SVG实现获取任意名字首字母并按要求画出柱形图,要求如下图(给出正确答案可追加悬赏),分不是问

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/16 00:40:45

求用javascript+SVG实现获取任意名字首字母并按要求画出柱形图,要求如下图(给出正确答案可追加悬赏),分不是问题,请各位帮忙!最好能有注解。


26个字母是被分成了6组,按照每组中含有字母个数增加柱形图高度。
/>createHistogram = function(document)
{
\x09var NewSVGElement = function(Q,A)//生成SVG元素
\x09{
\x09\x09var F;
\x09\x09Q = 'string' === typeof Q ? document.createElementNS('http' + '://www.w3.org/2000/svg',Q) : Q
\x09\x09for (F in A) F.indexOf('xlink:') ?
\x09\x09\x09Q.setAttribute(F,A[F]) ://不是xlink命名空间的属性
\x09\x09\x09Q.setAttributeNS('http' + '://www.w3.org/1999/xlink',F.substr(6),A[F])//是xlink命名空间的属性
\x09\x09return Q
\x09},Group = {},T = ['ABCD','EFGH','IJKL','MNOP','QRSTU','VWXYZ'],F;
\x09for (F = T.length;F--;)//向Group中初始化bins的数据
\x09\x09for (;T[F];T[F] = T[F].substr(1))
\x09\x09\x09Group[T[F].charAt(0)] = F

\x09return function(SVG,Q)
\x09{
\x09\x09var\x09Count = Array(6),//存放bins计数
\x09\x09\x09G,//<g>
\x09\x09\x09Max = 0,//存放最高矩形高度用於确定SVG绘图高度
\x09\x09\x09F;//临时变量|计数器变量
\x09\x09Q = Q.toUpperCase().split('')//转化成大写後单字分隔
\x09\x09for (;Q.length;Q.shift())//bins计数, 确定最高高度
\x09\x09{
\x09\x09\x09F = Group[Q[0]]
\x09\x09\x09Count[F] = (Count[F] || 0) + 1
\x09\x09\x09Max < Count[F] && (Max = Count[F])
\x09\x09}
\x09\x0950 * Max > SVG.getAttribute('height') && SVG.setAttribute('height',50 * Max)
\x09\x09SVG.appendChild(G = NewSVGElement('g',
\x09\x09{
\x09\x09\x09transform : 'translate(0 ' + SVG.getAttribute('height') + ') scale(1 -1)',//通过坐标变换将绘制设置为原点在左下角, 向右为x增, 向上为y增
\x09\x09\x09style : 'fill:blue;stroke:black'//默认填充样式
\x09\x09}))
\x09\x09for (F = 0;F < Count.length;++F)
\x09\x09\x09G.appendChild(NewSVGElement('rect',
\x09\x09\x09{
\x09\x09\x09\x09width : 50,
\x09\x09\x09\x09height : 50 * Count[F] || 1,
\x09\x09\x09\x09x : 50 * F,
\x09\x09\x09\x09y : 0
\x09\x09\x09}))
\x09\x09return SVG
\x09}
}(document)直接测试代码var TestSVG = document.createElementNS('http' + '://www.w3.org/2000/svg'
,'svg')
TestSVG.setAttribute('width',300)
TestSVG.setAttribute('height',400)
document.getElementsByTagName('body')[0].appendChild(TestSVG)
createHistogram(TestSVG,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),''Baidu编辑器简直愚蠢, 啥字符串都想搞成超链接有Bug说啊..懒得严格测试