js按住鼠标绘制线条代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了按住鼠标然后移动能够绘制线条的功能。

这个线条可以是随意的形状,代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

js按住鼠标绘制线条代码实例,这样的场景在实际项目中还是用的比较多的,关于js按住鼠标绘制线条代码实例就介绍到这了。

js按住鼠标绘制线条代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容