基于Canvas制作的写字板demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>写字板</title>
<script type="text/javascript" src="js/script.js" ></script>
<style>
*{
margin: 0;
padding: 0;
}
#canvas{
display: block;
margin:0 auto;
}
p{
margin-top: 10px;
text-align: justify;
text-align: center;
font-weight: bold;
font-size: 30px;
}
</style>
</head>
<body>
<canvas id="canvas">
此浏览器不支持canvas
</canvas>
<p>刷新页面以清空</p>
</body>
</html>
script.js
var canvasWidth = 600;
var canvasHeight = 600;
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
var isMouseDown = false;
var lastLoc; //储存鼠标上一次的坐标
var curLoc; //储存鼠标当前坐标
drawGrid(context); //绘制米字格
canvas.onmousedown = function(event){
event.preventDefault(); //阻止浏览器的默认响应事件
isMouseDown = true;
lastLoc = windowToCanvas(canvas,event.clientX,event.clientY);
}
canvas.onmouseup = function(event){
event.preventDefault();
isMouseDown = false;
}
canvas.onmouseout = function(event){
event.preventDefault();
isMouseDown = false;
}
canvas.onmousemove = function(event){
event.preventDefault();
if(isMouseDown == true){
curLoc = windowToCanvas(canvas,event.clientX,event.clientY);
context.beginPath();
context.moveTo(lastLoc.x,lastLoc.y);
context.lineTo(curLoc.x,curLoc.y);
context.lineWidth = 20;
context.lineCap = "round";
context.lineJoin = "round";
context.strokeStyle = "black";
context.stroke();
lastLoc = curLoc;
}
}
}
//将鼠标在整个页面中的坐标转换成在canvas中的坐标,坐标储存在一个对象中
function windowToCanvas(canvas,x,y){
var box = canvas.getBoundingClientRect();
return {x:Math.round(x-box.left),y:Math.round(y-box.top)};
}
function drawGrid(ctx){
ctx.save();
ctx.beginPath();
ctx.moveTo(2,2);
ctx.lineTo(canvasWidth-2,2);
ctx.lineTo(canvasWidth-2,canvasHeight-2);
ctx.lineTo(2,canvasHeight-2);
ctx.closePath(); //自动封闭图形
ctx.lineWidth = 4;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(canvasWidth,canvasHeight);
ctx.moveTo(canvasWidth-0,0);
ctx.lineTo(0,canvasHeight-0);
ctx.moveTo(canvasWidth/2,0);
ctx.lineTo(canvasWidth/2,canvasHeight);
ctx.moveTo(0,canvasHeight/2);
ctx.lineTo(canvasHeight,canvasHeight/2);
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.restore();
}