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:
<svg width="640" height="400" xmlns="http://www.w3.org/2000/svg" id="svgColumn"> <text x="200" y="20" font-size="20">SVG 华东地区手机12个月的数据 柱状图</text> <line x1="20" y1="380" x2="620" y2="380" stroke="black" stroke-width="1.5" /> <line x1="20" y1="380" x2="20" y2="1" style="stroke: black; stroke-width: 1.5" /> <path d="M600 360 L620 380 L600 400 Z" style="stroke: black; stroke-width: 1" /> <path d="M1 20 L20 1 L40 20 Z" style="stroke: black; stroke-width: 1" /> </svg>
HTML file:
<p id="svg1"> <embed src="./baidu34-36(svg-canvas)/column.svg" id="embed" width="640" height="400" type="image/svg+xml"> </p>
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 the setAttribute()
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!