html 鼠标拖动生成矩形SVG

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 鼠标拖动生成矩形SVG相关的知识,希望对你有一定的参考价值。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style>
body{
  margin:0;
  padding:0;
  overflow:hidden;
}
svg{
  position:absolute;
  width:100%;
  height:100%;
  left:0;
  top:0;
}
path{
  fill:none;
  stroke:red;
}
</style>
<script>
window.onload = function() {
  var svg = document.querySelector("svg");
  svg.setAttribute("width", innerWidth);
  svg.setAttribute("height", innerHeight);
  
  var rect;
  
  svg.addEventListener("mousedown", function(e) {
    rect = document.createElementNS(this.namespaceURI, "path");
    rect._d = "M" + e.clientX + "," + e.clientY;
    rect._d2 = "H" + e.clientX + "Z";
    this.appendChild(rect);
  }, false);
  
  svg.addEventListener("mousemove", function(e) {
    if (rect) {
      var d = rect._d + "H" + e.clientX + "V" + e.clientY + rect._d2;
      rect.setAttribute("d", d);
    }
  }, false);
  
  svg.addEventListener("mouseup", function(e) {
    rect = null;
  }, false);
  
  svg.addEventListener("mouseleave", function(e) {
    rect = null;
  }, false);
}
</script>
</head>
<body>
<svg></svg>
</body>
</html>

以上是关于html 鼠标拖动生成矩形SVG的主要内容,如果未能解决你的问题,请参考以下文章

SVG 矩形在鼠标悬停时显示 HTML 标题

C# GDI绘制矩形框,鼠标左键拖动可移动矩形框,滚轮放大缩小矩形框

WPF程序里,有一个ListView,想要在其中拖动鼠标,生成一个矩形框,并选中矩形框中的item元素,该怎么做

如何将子元素以外的元素用作拖动手柄?

如何将鼠标悬停在 SVG 矩形上?

SVG悬停矩形改变颜色