canvas簡單畫板效果

螞蟻小編發表於2018-05-24
分享一段程式碼例項,它實現了簡單的畫板效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload = function() {
  var oC = document.getElementById('c1');
  var oGC = oC.getContext('2d');
  oC.onmousedown = function(ev) {
    var ev = ev || window.event;
    oGC.moveTo(ev.clientX - oC.offsetLeft, ev.clientY - oC.offsetTop);
    document.onmousemove = function(ev) {
      var ev = ev || window.event;
      oGC.lineTo(ev.clientX - oC.offsetLeft, ev.clientY - oC.offsetTop);
      oGC.stroke();
    };
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
};
</script>
</head>
<body>
<div>
  <canvas id="c1" width="400" height="450"></canvas>
</div>
</body>
</html>

相關文章