canvas寫字板功能程式碼例項

antzone發表於2017-04-18

分享一段程式碼例項,它利用canvas實現了寫字板功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="container" style="background:#666"></canvas>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var container = document.getElementById('container');
var context = container.getContext('2d');
 
var paint = false; //判斷是否需要繪畫
var mouseX = 0,
  mouseY = 0,
  nowX = 0,
  nowY = 0; //儲存座標記錄
 
var position = {
  reset: function(actionX, actionY, goalX, goalY) { //座標替換
    paint = true;
    var order = "" + actionX + "=" + goalX + "," + actionY + "=" + goalY;
    eval(order);
    console.log(order);
  },
  init: function() { //座標清零
    console.log("init");
    paint = false;
    mouseX = 0;
    mouseY = 0;
    nowX = 0;
    nowY = 0;
  }
}
 
var canvas = {
  init: function() { //canvas初始化
    context.strokeStyle = "blue";
    context.strokeRect(0, 0, 300, 200)
  },
  draw: function(lastX, lastY, nowX, nowY) { //canvas劃線
    context.strokeStyle = "yellow";
    context.lineWidth = 2;
    context.beginPath();
    context.moveTo(lastX, lastY);
    context.lineTo(nowX, nowY);
    context.stroke();
    position.reset('mouseX', 'mouseY', nowX, nowY);
  },
  redraw: function() { //canvas重繪
    position.init();
  },
}
$('#container').mousedown(function(e) {
  position.reset('mouseX', 'mouseY', e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
  console.log(mouseX + ":" + mouseY);
})
$('#container').mousemove(function(e) {
  if (paint) {
    console.log(mouseX + ":" + mouseY);
    position.reset('nowX', 'nowY', e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
    canvas.draw(mouseX, mouseY, nowX, nowY);
  }
})
$("#container").mouseup(function(e) {
  if (paint) {
    position.init();
    // canvas.returnData();
  }
})
$("#container").mouseleave(function(e) {
  if (paint) {
    position.init();
  }
})
</script>
</body>
</html>

相關文章