svg03——用 js 创建svg
文章目录
实际使用svg中,我们经常会用js去操作svg
一、核心API:
1、创建图形:ns 指命名空间,tagName 是标签名,例如svg、rect
document.createElementNS(ns, tagName)2、添加子节点
element.appenChild(childElement)3、获取、设置属性
element.getAttribute(name)
element.setAttribute(name, value)二、实例
<div id="svgArea"></div><script>
// 命名空间
var SVG_NS = "http://www.w3.org/2000/svg"
var svgArea = document.getElementById('svgArea')
// 1、创建svg容器
var svg = document.createElementNS(SVG_NS, 'svg')
// 2、创建svg中的 tag, 如rect
var tag = document.createElementNS(SVG_NS, 'rect')
// 3、设置tag的属性
tag.setAttribute('width', "100")
tag.setAttribute('height', "100")
tag.setAttribute('fill', "rgba(255,255,255,0)")
tag.setAttribute('stroke-width', "1")
tag.setAttribute('stroke', "rgb(0,0,255)")
tag.setAttribute('x', '20')
tag.setAttribute('y', '20')
// 4、将tag塞进svg中
svg.appendChild(tag)
// 5、将svg塞进指定容器
svgArea.appendChild(svg)
</script>实际效果:


评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论