生活随笔
收集整理的這篇文章主要介紹了
基于SVG的鼠标动态绘制矩形和动态放置图片
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
web開發(fā)中經(jīng)常會(huì)遇到需要在圖片上或畫布上使用鼠標(biāo)動(dòng)態(tài)繪制圖形,或者用圖形或者小圖片標(biāo)注位置的需求,這里選擇使用svg來實(shí)現(xiàn)。
一、在html中添加svg標(biāo)簽,并在其中放置圖片(做背景)
<svg xmlns="http://www.w3.org/2000/svg" id="svgId" enable-background="new 0 0 900 454"viewBox="0 0 900 454" x="0px" y="0px" width="900" height="454" version="1.1"xml:space="preserve"><image id="imgId" x="0" y="0" width="900" height="454" href="your img_url"></image>
</svg>
二、繪制矩形
添加鼠標(biāo)事件的監(jiān)聽函數(shù),并在其中調(diào)用繪制矩形的函數(shù)。
function rectMouseEventBind() {let svg
= document
.getElementById("svgId");let isComplete
;svg
.onmousedown = function (ev
) {let ce
= ev
|| event
;x1
= ce
.offsetX
;y1
= ce
.offsetY
;isComplete
= false;};svg
.onmousemove = function (ev
) {let ce
= ev
|| event
;let nx1
= ce
.offsetX
;let ny1
= ce
.offsetY
;if (!isComplete
){if (((nx1
- x1
) > 10 || (ny1
- y1
) > 10) && nx1
> 0 && ny1
> 0) {drawRect(x1
, y1
, nx1
- x1
, ny1
- y1
, 0);}}};svg
.onmouseup = function (ev
) {let ce
= ev
|| event
;x2
= ce
.offsetX
;y2
= ce
.offsetY
;drawRect(x1
, y1
, x2
- x1
, y2
- y1
, 0);isComplete
= true;};
}
繪制矩形函數(shù)
function drawRect(px
, py
, width
, height
, id
) {let svg
= document
.getElementById("svgId");let delRect
= document
.getElementById(id
);if (delRect
!= null) {delRect
.remove();}let rect
= document
.createElementNS("http://www.w3.org/2000/svg", "rect");if (px
>= 0 && py
>= 0 && width
>= 0 && height
>= 0) {rect
.setAttribute("id", id
);rect
.setAttribute("x", px
);rect
.setAttribute("y", py
);rect
.setAttribute("width", width
);rect
.setAttribute("height", height
);rect
.setAttribute("style", "fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0);fill-opacity:0.1;");svg
.appendChild(rect
);}
}
三、打點(diǎn)
這里使用放置更小圖片的方式
添加鼠標(biāo)事件的監(jiān)聽函數(shù),并在其中調(diào)用繪制添加小圖片的函數(shù)。
function pointMouseEventBind() {let svg
= document
.getElementById("svgId");let isComplete
;svg
.onmousedown = function (ev
) {let ce
= ev
|| event
;x1
= ce
.offsetX
;y1
= ce
.offsetY
;drawImg(x1
, y1
, 0);};svg
.onmouseup = function (ev
) {completeFlag
= true;};
}
繪制小圖片
function drawImg(px
, py
, width
, height
, id
) {let svg
= document
.getElementById("svgId");let svgImg
= document
.createElementNS('http://www.w3.org/2000/svg', 'image');svgImg
.setAttribute("id", id
);svgImg
.setAttribute("x", px
- 11);svgImg
.setAttribute("y", py
- 24);svgImg
.setAttribute('height', '32');svgImg
.setAttribute('width', '20');svgImg
.setAttribute('href', 'your img url');svg
.appendChild(svgImg
);
}
四、最終效果
總結(jié)
以上是生活随笔為你收集整理的基于SVG的鼠标动态绘制矩形和动态放置图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。