Use the <svg> tag to insert content into the web page directly, become part of the DOM, and then you can use CSS and JS for control.
A simple circle:
<svg width=400 heihgt=300 id=testSvg> <circle cx=100 cy=100 r=50 fill=red stroke=black stroke-width=2 id=testCircle></circle></svg>//You can use CSS to control the style of SVG, but the attributes are different from ordinary web elements <style type=text/css> #testSvg {border:1px solid #ccc;} #testSvg circle { fill: red; stroke: blue; stroke-width: 3; }</style>//You can use JS to operate SVG, create simple animations, etc. <script type=text/javascript> var circle = document.getElementById(testCircle); circle.addEventListener(click, function(e) { console.log(Click circle ...); circle.setAttribute(r, 65); }, false);</script>//In addition to using JS, you can use SVG's own animate to create animation effects <svg width=400 height=300 id=testSvg> <circle cx=100 cy=100 r=50 id=testCircle> <animate attributeName=cx from=100 to=300 dur=2s repeatCount=indefinite></animate> </circle></svg>Display effect:
Insert svg file You can use <img> <embed> <object> <iframe> and other tags to insert SVG files into web pages.
Except for <img> , the double tag should be used.
//Use the <img> tag <img src=test.svg' />//or the base64 encoding of SVG <img src=data:image/svg+xml;base64,[data] />//Use the <embed> tag <embed id=embedSvg type=image/svg+xml src=test.svg></embed>//Get SVG DOMvar embedSvg = document.getElementById(embedSvg).getSVGDocument();console.log(SVG DOM: , embedSvg);//Use the <object> tag <object id=objectSvg type=image/svg+xml data=test.svg></object>//Get SVG DOMvar objectSvg = document.getElementById(objectSvg).getSVGDocument();console.log(SVG DOM: , objectSvg);//Use the <iframe> tag <iframe id=iframeSvg src=test.svg></iframe>//Get SVG DOMvar iframeSvg = document.getElementById(iframeSvg).contentDocument;console.log(SVG DOM: , iframeSvg);
SVG DOM output:
Use svg as background image for other web page elements
This is a disguised way to insert svg into a web page, that is, use svg as an ordinary picture and cannot display animation effects.
<style type=text/css>.svg-div {width:400px;height:300px;background:url(test.svg) no-repeat center / 50%;border:1px solid #ccc;}</style><div class=svg-div></div>Effect:
Read SVG source codeBecause the SVG file is essentially a piece of XML text, the SVG source code can be read by reading the XML code.
var svgStr = new XMLSerializer().serializeToString(document.getElementById(testSvg));console.log(svgStr);Summarize
This is the end of this article about the various ways to insert SVG on HTML pages. For more relevant html insert SVG content, please search for previous articles from Wulin.com or continue browsing the related articles below. I hope everyone will support Wulin.com in the future!