DEV Community

NikiMunger
NikiMunger

Posted on

createElementNS、setAttribute()、SVG 的 viewBox 属性、`<svg>`

createElementNS

document.createElementNS(namespaceURL, tagName)
Enter fullscreen mode Exit fullscreen mode
  • namespaceURL(命名空间 URL)
    这是一个固定的字符串,用来告诉浏览器这个标签属于哪个规范。
    SVG 固定用:

    'http://www.w3.org/2000/svg'
    

    MathML 用:

    'http://www.w3.org/1998/Math/MathML'
    
  • tagName(元素名称)
    也就是你要创建的标签名称,例如:

    • 'svg'
    • 'circle'
    • 'rect'
    • 'path'

示例:在 SVG 命名空间里创建一个 <svg> 标签

document.createElementNS('http://www.w3.org/2000/svg', 'svg');
Enter fullscreen mode Exit fullscreen mode

setAttribute()

setAttribute(name, value) 是 DOM API,用于:
给元素添加 / 修改 HTML 或 SVG 的属性(attribute)

它可以操作任何标签上的属性,包括:

  • HTML 属性
  • SVG 属性
  • 自定义属性(data-*)
  • 布尔属性(disabled)
  • 非标准属性(自定义扩展)

最常用形式

element.setAttribute('属性名', '属性值');
Enter fullscreen mode Exit fullscreen mode

为什么要用 setAttribute?

因为 某些属性不能直接用点语法赋值,尤其是:

  • SVG 属性
  • 带中划线的属性(如 stroke-width、data-id)
  • 不存在于 DOM property 的 HTML 属性

例如:

circle.stroke-width = 4;
Enter fullscreen mode Exit fullscreen mode

不会生效

circle.setAttribute('stroke-width', 4);
Enter fullscreen mode Exit fullscreen mode

才能生效


SVG 的 viewBox 属性

viewBox 决定了:
SVG 内部的“坐标系统范围”是什么,以及如何映射到屏幕上的显示区域。
它定义了 你在 SVG 画布里“看到的那一块区域”。

viewBox 的语法

viewBox="minX minY width height"
Enter fullscreen mode Exit fullscreen mode
  • minX:视图窗口的左上角 X 坐标
  • minY:视图窗口的左上角 Y 坐标
  • width:视图窗口的宽度
  • height:视图窗口的高度

SVG 的两个坐标系统

  • SVG 有两个坐标系统: 外部尺寸(实际显示大小) 由 width / height 或 CSS 控制
  • 内部坐标系(viewBox 决定)

例子:

<svg width="200" height="200" viewBox="0 0 100 100">
Enter fullscreen mode Exit fullscreen mode

含义:

  • 外部尺寸 = 200x200 像素
  • 内部绘图坐标 = 100x100 单位
  • 相当于你把 100x100 的世界压缩放大到 200x200 来显示

结果:

  • 在 SVG 里 (0,0) 是左上角
  • (100,100) 是右下角
  • 一个单位 = 2 像素(因为 200/100 = 2)

<svg>

所有 SVG 图形(rect, circle, path),都必须放在 <svg> 内才能渲染。

元素 作用 与对方关系
<svg> 整个进度条的画布 父节点
<rect> 画出来的边框 子节点

Top comments (0)