--- title: SVG In HTML Introduction slug: Web/SVG/Tutorial/SVG_In_HTML_Introduction tags: - SVG translation_of: Web/SVG/Tutorial/SVG_In_HTML_Introduction ---
本文及其相关示例展示了如何使用内联的 SVG 给一个表单提供背景图片,它展示了如何按照编写常规XHTML代码相同的方式来通过JavaScript 和 CSS 操作图片。注意,该示例仅在支持XHTML(非HTML)并集成了SVG的浏览器中正常工作。
源码如下: 查看示例
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>XTech SVG Demo</title> <style> stop.begin { stop-color:yellow; } stop.end { stop-color:green; } body.invalid stop.end { stop-color:red; } #err { display:none; } body.invalid #err { display:inline; } </style> <script> function signalError() { document.getElementById('body').setAttribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legend>HTML Form</legend> <p><label>Enter something:</label> <input type="text"/> <span id="err">Incorrect value!</span></p> <p><input type="button" value="Activate!" onclick="signalError();" /></p> </fieldset> </form> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;"> <linearGradient id="gradient"> <stop class="begin" offset="0%"/> <stop class="end" offset="100%"/> </linearGradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" /> </svg> </body> </html>
该页面主要是常规的XHTML、CSS和Javascript,唯一有趣的部分就是包含了<svg>元素。该元素及其子元素都被声明在SVG的命名空间内。它包含一个渐变和两个渐变填充的形状。该渐变颜色的终值颜色由CSS设置,当用户在表单中输入了错误信息,脚本会给<body>设置一个invalid
属性,样式规则将渐变颜色的end-stop
颜色设置为红色(另一个样式规则用于展示错误提示信息)
该方法有如下几点需要注意:
如果需要给一个内嵌的SVG元素通过DOM方法添加一个有外链的图片,我们需要使用 setAttributeNS
来设置外链地址 href
. 示例如下:
var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "move.png");
viewBox属性创建了一个与SVG图片坐标系相关联的逻辑坐标系,通过这种方式我们的图片被放置到了一个100x100的视觉系中。
preserveAspectRatio属性指定了需要预设的数据,即指定了再有效大小内图片的居中、适配图片最大宽高,并裁切掉了多余部分。
样式属性指定了SVG在form背景中的位置。