1.鼠标划线
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>鼠标画线</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');//webgl:3D绘图
oC.onmousedown = function(ev){ //鼠标按下
var ev = ev || window.event
// offsetLeft:元素的左外边框至包含元素的左内边框之间的像素距离
//canvas距离屏幕的距离(oC.offsetLeft,oC.offsetTop)
//鼠标按下的初始坐标点,此坐标点是相对于屏幕的,所以还需要减掉canvas距离屏幕得距离
oGC.moveTo(ev.clientX-oC.offsetLeft,ev.clientY-oC.offsetTop)
document.onmousemove = function(ev){ //鼠标移动的时候
var ev = ev || window.event
oGC.lineTo(ev.clientX-oC.offsetLeft,ev.clientY-oC.offsetTop)
console.log('lineTo-----------')
console.log(ev.clientX-oC.offsetLeft,ev.clientY-oC.offsetTop)
oGC.stroke()
}
document.onmouseup = function(ev){
document.onmousemove = null
document.onmouseup = null
}
}
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
</body>
</html>
2.方块移动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>鼠标画线</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');//webgl:3D绘图
var num = 0;
oGC.fillRect(0,0,100,100)
oGC.fillStyle = 'red'
setInterval(function(){
num++
oGC.clearRect(0,0,oC.width,oC.height)
oGC.fillRect(num,num,100,100)
},30)
}
</script>
</head>
<body>
<!-- width="400" height="400" 此处是画布真正的宽高
#c1{background: white;width:400px;height:400px} 此处宽高只是默认宽300,高150的等比例缩放
-->
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
<!-- canvas默认宽300,高150 -->
</body>
</html>
3.注意点
<body>
<!-- width="400" height="400" 此处是画布真正的宽高
#c1{background: white;width:400px;height:400px} 此处宽高只是默认宽300,高150的等比例缩放
-->
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
<!-- canvas默认宽300,高150 -->