js按住滑鼠繪製線條程式碼例項

antzone發表於2017-04-17

分享一段程式碼例項,它實現了按住滑鼠然後移動能夠繪製線條的功能。

這個線條可以是隨意的形狀,程式碼例項如下:

[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;
}
#canvas {
  background: #000;
}
</style>
<script>
window.onload = function() {
  var myCanvas = document.getElementById("canvas");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  var ext = myCanvas.getContext("2d"); //2d繪圖物件
  myCanvas.onmousedown = function(e) {
    var e = e || window.e;
    ext.beginPath();
    ext.moveTo(e.clientX - myCanvas.offsetLeft, e.clientY - myCanvas.offsetTop);
    document.onmousemove = function(e) {
      var e = e || window.e;
      ext.lineTo(e.clientX - myCanvas.offsetLeft, e.clientY - myCanvas.offsetTop);
      ext.stroke(); //連結起始點和終結點
      ext.strokeStyle = "blue"; //筆觸的顏色
    };
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
}        
</script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

相關文章