<canvas id="canvas" width="400" height="400" style="background: #ccc;"></canvas>
var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");

function onMouseMove(e) {
  var movePosition = {
    x: getMouse(e).x,
    y: getMouse(e).y
  };
  context.lineTo(movePosition.x, movePosition.y);
  context.stroke();
}

canvas.addEventListener("mousedown", function(e) {
  var curPosition = {
    x: getMouse(e).x,
    y: getMouse(e).y
  };
  context.beginPath();
  context.moveTo(curPosition.x, curPosition.y);
  console.log("curPosition: " + curPosition.x + "; " + curPosition.y);
  canvas.addEventListener("mousemove", onMouseMove, false);
}, false);

canvas.addEventListener("mouseup", function(e) {
  canvas.removeEventListener("mousemove", onMouseMove, false);
}, false);

// 获取鼠标的当前位置
function getMouse(event) {
  var event = event || window.event;
  var mouse = {};
  var x, y;
  if(event.pageX || event.pageY) {
    x = event.pageX;
    y = event.pageY;
  } else if(event.clientX || event.clientY) {
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    x = event.clientX + scrollLeft;
    y = event.clientY + scrollTop;
  }
  mouse.x = x;
  mouse.y = y;
  return mouse;
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.