随意绘制的效果图如下:
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>paint</title>
<script type="text/javascript" src="js/jquery-1.11.0.js" ></script>
<script type="text/javascript" src="js/bootstrap.js" ></script>
<link rel="stylesheet" href="css/bootstrap.css" />
<style>
body{
width: 100%;
height: 100%;
background: black;
}
canvas{
background: #fff;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="400" >
只是一个canvas而已
</canvas>
<script>
var oC=document.getElementById("canvas")
var oGc=oC.getContext("2d")
oC.onmousedown=function(e){
var disX=e.clientX-oC.offsetLeft //获取鼠标到窗口左边的距离
var disY=e.clientY-oC.offsetTop //获取鼠标到窗口头部的距离
oGc.moveTo(disX,disY)
document.onmousemove=function(e){
var disX=e.clientX-oC.offsetLeft
var disY=e.clientY-oC.offsetTop
oGc.strokeStyle="pink"
oGc.lineWidth = 8
oGc.lineTo(disX,disY)
oGc.stroke()
}
document.onmouseup=function(){
document.onmousedown=null
document.onmousemove=null
}
}
</script>
</body>
</html>
实现原理:
通过计算出窗口的大小后,利用鼠标的点击和放开结合绘图的方法起来实现功能。