拖拽編寫SVG圖形化工具(二)
阿新 • • 發佈:2020-10-28
![](https://img2020.cnblogs.com/blog/1308525/202010/1308525-20201028143123871-1709751268.gif)
# getAttributesNs/setAttributesNs
```js
element.setAttributeNS(namespace,name,value)
```
- `namespace` 是指定屬性的名稱空間的一個字串。
- `name` 是標識要設定的屬性的一個字串。
- `value` 是新屬性的所需字串值。
新增/或者查詢一個新屬性或更改具有給定名稱空間和名稱的一個屬性的值。
> **setAttribute()**是DOM 1函式。**setAttributeNS()**是DOM 2函式
>
> 果屬性沒有定義的名稱空間字首,則第一個引數必須為**null**。您可以使用**setAttribute(),**但是為了保持一致性,建議堅持使用**setAttributeNS()**
# 應用demo
程式思路
首先我們看看程式碼對映
```js
// 按下
box.onmousedown = function (event) {
console.log(1);
// 移動
box.onmousemove=function () {
console.log(2);
}
// 抬起
box.onmouseup=function () {
console.log(3);
}
}
```
> 通過point拿到所有`circle` 圖形的原點
>
> line拿到直線的dom和path的dom
>
> 限制座標的範圍, 由於`circle`的半徑有一定長度,所以減去5做一定的限制
>
> ```js
> maxX = container.offsetWidth - 5
> maxY = container.offsetHeight - 5,
> // 滑鼠範圍限制
> function PointM(x, y) {
> return {
> x: Math.max(0, Math.min(maxX, x)),
> y: Math.max(0, Math.min(maxY, y))
> }
> }
> m = PointM(e.pageX, e.pageY);
> ```
>
> 當滑鼠點在path上可以通過fill 進行切換背景顏色
> ```js
> +circle[i].getAttributeNS(null, 'cx')
> ```
>
> 要知道我們通過`getAttributeNS` 拿到的是字串所以要進行轉化
> ```js
> ['p1', 'p2', 'c1', 'c2'].includes(id)
> ```
>
> 是為了保證按在是個點上面,然後後面的id容易報錯
整體的邏輯就是
滑鼠按下開始的時候,記錄當前的座標,拿到點選的那個dom
後續滑鼠移動的時候, 當前的座標-開始的座標的差值=本來應該指向的座標
並且移動的時候要設定一定的範圍,以便更新點不能離開當前的範圍
滑鼠離開的時候,關閉移動/鬆開的事件
```js
Document
code