web开发中经常会遇到需要在图片上或画布上使用鼠标动态绘制图形
,或者用图形或者小图片标注位置
的需求,这里选择使用svg来实现。
一、在html中添加svg标签,并在其中放置图片(做背景)
<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>
二、绘制矩形
- 添加鼠标事件的监听函数,并在其中调用绘制矩形的函数。
/**
*初始化绘制矩形的鼠标绑定事件
**/
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;
};
}
- 绘制矩形函数
/**
* 绘制矩形
**/
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中
svg.appendChild(rect);
}
}
三、打点
这里使用放置更小图片的方式
- 添加鼠标事件的监听函数,并在其中调用绘制添加小图片的函数。
/**
*初始化放置图片的鼠标绑定事件
**/
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);
}
四、最终效果