【发布时间】:2018-08-31 09:30:44
【问题描述】:
我正在创建类似 Google Analytic 的图表,使用 SVG 沿点绘制数据。我已经获取了一个函数,它将接受一个点数组并将它们构建到一个路径元素中,该元素被插入到 HTML 页面上的 SVG 中。这个功能在 Chrome、Firefox、Edge 和 Safari 上都成功了,但是当它到达 IE11 时它甚至不输出元素。
我相信兼容性问题在于 svgPath();功能。我读过 IE11 不支持 ES6 javascript,我想知道是否有人对 IE11 和 javascript 有更好的了解可以帮助诊断问题的原因。
仅供参考,如果我在它工作的浏览器上从 DOM 中复制路径代码并将其直接放在 HTML 中,它确实适用于 IE11。所以问题似乎完全出在 javascript 函数上,而不是 SVG 没有为 IE11 显示。
Javascript:
var points = [
[5, 10],
[10, 40],
[40, 30],
[60, 5],
[90, 45],
[120, 10],
[150, 45],
[200, 10]
];
// Render the svg <path> element
// I: - points (array): points coordinates
// - command (function)
// I: - point (array) [x,y]: current point coordinates
// - i (integer): index of 'point' in the array 'a'
// - a (array): complete array of points coordinates
// O: - (string) a svg path command
// O: - (string): a Svg <path> element
var svgPath = function svgPath(points, command) {
// build the d attributes by looping over the points
var d = points.reduce(function (acc, point, i, a) {return i === 0 ? 'M ' +
point[0] + ',' + point[1] :
acc + ' ' + command(point, i, a);},
'');
return '<path d="' + d + '" fill="none" stroke="grey" />';
};
// Svg path line command
// I: - point (array) [x, y]: coordinates
// O: - (string) 'L x,y': svg line command
var lineCommand = function lineCommand(point) {return 'L ' + point[0] + ' ' + point[1];};
var svg = document.querySelector('.svg');
svg.innerHTML = svgPath(points, lineCommand);
HTML:
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="1000"
height="200"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 200 50"
preserveAspectRatio="xMidYMid meet"
class="svg">
</svg>
函数应该返回的字符串,但不在 IE11 上:
<path d="M 5,10 L 10 40 L 40 30 L 60 5 L 90 45 L 120 10 L 150 45 L 200 10" fill="none" stroke="grey"></path>
Chrome 中的 Graph 屏幕截图: https://imgur.com/a/7ZvLkb9
IE11 中的 Graph 截图: https://imgur.com/a/iaS5OJK
最后是我获得 javascript 函数的来源: https://medium.com/@francoisromain/smooth-a-svg-path-with-cubic-bezier-curves-e37b49d46c74 https://codepen.io/francoisromain/pen/dzoZZj
【问题讨论】:
-
IE 上的 innerHTML 将无法正确创建 SVG 元素,您需要使用 document.createElementNS 在正确的命名空间中单独创建元素。我相信 innerHTML 已在 Edge 中得到修复,并且适用于所有其他现代浏览器。
-
我同意 Robert Longson 的观点:使用 javascript 创建 d 属性的值,然后使用
pathName.setAttributeNS(null,"d","M 5,10 L 10 40 L 40 30 L 60 5 L 90 45 L 120 10 L 150 45 L 200 10") -
感谢你们的帮助。保罗使用了你提到的技术,现在它已经奏效了!
标签: javascript html svg internet-explorer-11