<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>手写板</title>
<link href="css/demo.css" rel="stylesheet" />
<script src="js/jquery-1.10.2.min.js"></script>
<script>
var canvas, context;
var isMouseDown = false;
var startPoint = { x: 0, y: 0 };
var lineColor = "black";
function getPoint(x, y) {
var canvasOffset = canvas.getBoundingClientRect();//获取到canvas相对于浏览器的方位对象
return { x: x - canvasOffset.left, y: y - canvasOffset.top };
}
function clearCanvas() {
context.clearRect(0, 0, 400, 400);
draw();
}
window.onload = function () {
$(".dcolor").click(function () {
lineColor = $(this).attr("data-color");
});
draw();
canvas.onmousedown = function (e) {
isMouseDown = true;
startPoint = getPoint(e.clientX, e.clientY);//获取起点相对于canvas的坐标
}
canvas.onmouseup = function () {
isMouseDown = false;
}
canvas.onmouseout = function () {
isMouseDown = false;
}
canvas.onmousemove = function (e) {
if (isMouseDown) {
var endPoint = getPoint(e.clientX, e.clientY);
context.beginPath();
context.strokeStyle = lineColor;
context.lineWidth = 3;
context.moveTo(startPoint.x, startPoint.y);
context.lineTo(endPoint.x, endPoint.y);
context.stroke();
startPoint = endPoint;
}
}
}
function draw() {//画米字格
canvas = document.getElementById("canvas");//获取到canvas对象,演员
context = canvas.getContext("2d");//canvas画图的环境,相当于演员表演的舞台
canvas.width = 400;//设置canvsa宽度
canvas.height = 400;//设置canvas高度
context.beginPath();//开始一个路径
context.strokeStyle = "red";//设置线的颜色
context.lineWidth = 4;//设置线的粗细
context.moveTo(0, 0);
context.lineTo(400, 0);
context.lineTo(400, 400);
context.lineTo(0, 400);
context.closePath();//形成一个闭合的图形
context.stroke();//开始绘制
context.beginPath();
context.lineWidth = 1;
context.moveTo(0, 0);
context.lineTo(400, 400);
context.moveTo(400, 0);
context.lineTo(0, 400);
context.moveTo(200, 0);
context.lineTo(200, 400);
context.moveTo(0, 200);
context.lineTo(400, 200);
context.stroke();//开始绘制
}
</script>
</head>
<body>
<div id="main">
<canvas id="canvas"></canvas>
<div id="colors">
<div class="dcolor" data-color="black" id="cbalck"></div>
<div class="dcolor" data-color="red" id="cred"></div>
<div class="dcolor" data-color="green" id="cgreen"></div>
<div class="dcolor" data-color="blue" id="cblue"></div>
<div class="dcolor" data-color="pink" id="cpink"></div>
<div class="dclear"><a href="javascript:;" onclick="clearCanvas()">清除</a></div>
</div>
</div>
</body>
</html>