关于前端: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>
实际效果:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理