<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鼠标,触屏写字</title>
</head>
<style>
#wrap{
height:400px;
width:400px;
margin:100px auto;
}
#write{
height:400px;
width:400px;
}
</style>
<body>
<div id="wrap">
<canvas id="write" height="400" width="400"></canvas>
</div>
</body>
<script>
window.onload = function(){
var write = document.getElementById('write');
var ctx = write.getContext('2d');
var h = ctx.canvas.height;
var w = ctx.canvas.width;
var isMouseDown = false;
var lastLoc = {x:0,y:0};
drawGruid();
write.onmousedown = function(e){
e.preventDefault();//阻止默认的事件响应
isMouseDown = true;
lastLoc = winToCanvas(e.clientX,e.clientY);
// console.log(lastLoc.x+","+lastLoc.y);
}
write.onmouseup = function(e){
e.preventDefault();
isMouseDown = false;
}
write.onmousemove = function(e){
e.preventDefault();
if(isMouseDown){
//console.log("mouse move");
var curLoc =winToCanvas(e.clientX,e.clientY);
ctx.beginPath();
ctx.moveTo(lastLoc.x,lastLoc.y);
ctx.lineTo(curLoc.x,curLoc.y);
ctx.strokeStyle = "black";
ctx.lineWidth = 10;
ctx.stroke();
lastLoc = curLoc;
}
}
write.onmouseout = function(e){
e.preventDefault();
isMouseDown = false;
}
// 屏幕与画布坐标转换
function winToCanvas(x,y){
var box = write.getBoundingClientRect();
return {x:Math.round(x-box.left),y:Math.round(y-box.top)};
}
function drawGruid(){
//大边框
ctx.save();
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(w,0);
ctx.lineTo(w,h);
ctx.lineTo(0,h);
ctx.closePath();
ctx.lineWidth = 10;
ctx.stroke();
//米字格
ctx.beginPath();
ctx.lineWidth=1;
ctx.moveTo(0,0);
ctx.lineTo(w,h);
ctx.moveTo(w,0);
ctx.lineTo(0,w);
ctx.moveTo(0,h/2);
ctx.lineTo(w,h/2)
ctx.moveTo(w/2,0);
ctx.lineTo(w/2,h)
ctx.stroke();
ctx.restore();
}
}
</script>
</html>
少写了lineCap = ‘round’
用粗线条画线会有间隙,在教学视频的3-1章节第2分45秒有解释