关于前端:svg03用-js-创建svg

1次阅读

共计 792 个字符,预计需要花费 2 分钟才能阅读完成。

理论应用 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>
实际效果:

正文完
 0