<!DOCTPE html>
<html>
<head>
<meta charset = "utf-8">
<title>简易画笔</title>
<style>
*{padding:0;margin:0;}
body,html{width:100%;overflow:hidden;}
body{background-color:pink;}
#test{
background-color:white;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto auto;/*上下auto,左右auto*/
}
</style>
</head>
<body>
<canvas id="test" height="800px" width="800px">
<span>您的浏览器不支持canvas,请换成萌萌的谷歌</span>
</canvas>
</body>
<script>
window.οnlοad= function(){
var canvas = document.querySelector("#test");
if(canvas.getContext){
var c = canvas.getContext("2d");
}
//在画布上绑定鼠标按下的监听
canvas.οnmοusedοwn=function(ev){
//alert("按个球尼按");
//获得触发事件的源 不同浏览器得到方式不一样
ev=ev || window.event;
//针对IE做的兼容
//判断全局俘获对象,有的话就设置俘获
if(canvas.setCapture){
canvas.setCapture();
}
//清除路径容器
c.beginPath();
//设置起点:鼠标按下的点
c.moveTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop);
//监听鼠标移动过程
document.onmousemove = function(ev){
ev=ev || window.event;
c.strokeStyle="red";
//c.strokeStyle=mycolor;
c.save();//压入栈
//设置终点
c.lineTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop);
//弹出栈
c.restore();
c.stroke();//绘制路径
}
//鼠标松开时执行不绘制的代码
document.onmouseup = function(ev){
//将鼠标放开和鼠标移动的监听事件清空
document.οnmοusemοve=document.οnmοuseup=null;
//如果有释放对象,就释放全局对象
if(document.releaseCapture){
//释放对象
document.releaseCapture();
}
}
return false;//避免浏览器的其他默认事件对操作的影响
}
}
</script>
</html>