<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>两点之间画折线</title>
<style type="text/css">
#canvas {
background: #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="500"></canvas>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
var canvas = document.getElementById("canvas"); // 得到画布
var ctx = canvas.getContext("2d"); // 得到画布的上下文对象
var flag = false;
var x = 0; // 鼠标开始移动的位置X
var y = 0; // 鼠标开始移动的位置Y
var url = "";
var xyArr = [];
$("canvas")
.mousedown(function(e) {
flag = true;
x = e.offsetX; // 鼠标落下时的X
y = e.offsetY; // 鼠标落下时的Y
// xyArr.push({ x: x, y: y });
})
.mouseup(function(e) {
flag = false;
url = $("canvas")[0].toDataURL(); // 每次 mouseup 都保存一次画布状态
xyArr.push({ x: x, y: y });
console.log(xyArr);
})
.mousemove(function(e) {
drawLine(e); // 绘制方法
loadImage();
});
function drawPencil(e) {
if (flag) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke(); // 调用绘制方法
} else {
ctx.beginPath();
ctx.moveTo(x, y);
}
}
function drawRect(e) {
if (flag) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.strokeRect(x, y, e.offsetX - x, e.offsetY - y);
}
}
function drawLine(e) {
if (flag) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
}
function loadImage() {
var img = new Image();
img.src = url;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
</script>
转载于:https://my.oschina.net/ndweb/blog/3057882