This article mainly introduces how to operate svg with JS to draw pictures. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it
Total There are 3 files: svg file, html file, js file.
There is an svg image, using the embed tag, introduced into the html file
svg file:
HTML file:
If your svg is written directly in the html file, then svg and HTML share a document, you can directly use document.getElementById(svg id) can be obtained.
However, under normal circumstances, it is not recommended to mix them together. For example, the column image here is a separate svg file, and then inserted into HTML using embed.
At this time, again If you want to get svg, you need to use:getSVGDocument();
Usage method: Get the embed node first, then the svg document, and then the svg node:
function drawColumn(data) { var nameSpace = 'http://www.w3.org/2000/svg'; var max = Math.max.apply(null, data); var proportion = 350/max; var interval = 35; //column间隔 var columnStyle = 'stroke: blue; fill: orange'; var embedSVG = document.getElementById('embed').getSVGDocument().getElementById('svgColumn');//关键代码:embedSVG的赋值。最后的getElementById('svgColumn'),是svg文件中,svg标签的id for (let singleColumn of data) { var rect = document.createElementNS(nameSpace,'rect');//creat新的svg节点,rect。 rect.style = columnStyle; //给rect节点设置style height = singleColumn*proportion; rect.setAttribute('width', '30'); //使用setAttribute来设置rect节点属性 rect.setAttribute('height', height); rect.setAttribute('x', interval); rect.setAttribute('y', 380-height); embedSVG.appendChild(rect); //将这个新的rect节点 添加到svg节点里 interval += 45 } }
In addition, unlike HTML element objects that can directly assign values to some attributes, SVG element objects need to set attribute values by calling thesetAttribute()
method.
Using rect.width = 30 does not work.
Related recommendations:
How to implement one-way binding in js (with code)
How to use JS Get local latitude and longitude
The above is the detailed content of How to operate svg with JS to draw pictures. For more information, please follow other related articles on the PHP Chinese website!