SVG拖動繪製矩形程式碼例項

螞蟻小編發表於2018-06-02
分享一段程式碼例項,通過拖動就可以繪製一個矩形。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!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>

相關文章