Display Inline SVG Using the <img> Tag

October 19, 2011

SVG can be embedded into HTML documents with the <img> tag. Even better, standards-compliant browsers will also accept inline base-64 encoded SVG as a data URI. For example this figure:

was created with this tag:

<img width="400" class="figure" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiCiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiCiAgIHhtbG5zOmlua3NjYXBlPSJodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy9uYW1lc3BhY2VzL2lua3NjYXBlIgogICB3aWR0aD0iNDQ5LjEwNTE2IgogICBoZWlnaHQ9IjQyNS43MTQyOSIKICAgaWQ9InN2ZzIiCiAgIHZlcnNpb249IjEuMSIKICAgaW5rc2NhcGU6dmVyc2lvbj0iMC40OC4wIHI5NjU0IgogICBzb2RpcG9kaTpkb2NuYW1lPSJzdGFyLnN2ZyI+CiAgPGRlZnMKICAgICBpZD0iZGVmczQiPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpw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N0cm9rZS1kYXNoYXJyYXk6bm9uZTtzdHJva2UtZGFzaG9mZnNldDowIgogICAgICAgaWQ9InBhdGgzNzc1IgogICAgICAgc29kaXBvZGk6c2lkZXM9IjUiCiAgICAgICBzb2RpcG9kaTpjeD0iMTkxLjQyODU3IgogICAgICAgc29kaXBvZGk6Y3k9IjE0Ni43MjA3OSIKICAgICAgIHNvZGlwb2RpOnIxPSIyMDYuNDI3MzQiCiAgICAgICBzb2RpcG9kaTpyMj0iOTMuMjYwNTY3IgogICAgICAgc29kaXBvZGk6YXJnMT0iLTEuNTcwNzk2MyIKICAgICAgIHNvZGlwb2RpOmFyZzI9Ii0wLjk4MDYyODQ5IgogICAgICAgaW5rc2NhcGU6ZmxhdHNpZGVkPSJmYWxzZSIKICAgICAgIGlua3NjYXBlOnJvdW5kZWQ9IjAiCiAgICAgICBpbmtzY2FwZTpyYW5kb21pemVkPSIwLjAxNSIKICAgICAgIGQ9Ik0gMTg4Ljk5NjA0LC02MS4zODQxNDUgMjQxLjc0MDIsNjcuOTU0NjU1IDM4NC45NjU3Miw4NC4yNjM1OTIgMjgxLjA5OTQ0LDE3My44MTUwNCAzMTUuMjQ0NTMsMzEzLjM3MzA5IDE5Ny44MDQ4MywyNDEuODQxMjggNzEuMDM4MDU3LDMxNS43MzE1OCAxMDMuMDI3NDEsMTc3LjM5MDA5IC0yLjE0Mzk3MTIsODIuMjcwMDIyIDEzMS44OTU0Miw3NS4zNDgxOTQgeiIKICAgICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Mi4xNTAzMywzMDQuODQ2MzEpIgogICAgICAgaW5rc2NhcGU6dHJhbnNmb3JtLWNlbnRlci14PSIwLjAxNzcwMzI1OSIKICAgICAgIGlua3NjYXBlOnRyYW5zZm9ybS1jZW50ZXIteT0iLTE5LjU0NzA3NCIgLz4KICA8L2c+Cjwvc3ZnPgo="></img>

In other words, it's possible to generate and display vector graphics client-side without manipulating a DOM representation. This could be useful, for example, when generating complex vector graphics within a Web Worker, which lacks DOM access.