canvas制作鼠标绘图: 原理:获取开始点击的点 和鼠标移动后的点
所用知识:event对象 canvas绘图
鼠标绘图.gif
window.onload=function (){
var myCanvas=document.querySelector('#myCanvas');
var cxt=myCanvas.getContext('2d');
myCanvas.onmousedown=function (event) {
var e=event || window.event;
//获取鼠标开始点击位置
cxt.moveTo(e.clientX-myCanvas.offsetLeft,e.clientY-myCanvas.offsetTop);
document.onmousemove=function (event) {
var e=event || window.event;
//鼠标移动位置
cxt.lineTo(e.clientX-myCanvas.offsetLeft,e.clientY-myCanvas.offsetTop);
cxt.stroke();
}
document.onmouseup=function () {
document.onmouseup=null;
document.onmousemove=null;
}
}
}
方块移动小案例: 坐标的改变
window.onload=function (){
var myCanvas=document.querySelector('#myCanvas');
var cxt=myCanvas.getContext('2d');
var num=0;
cxt.fillRect(0,0,100,100);
setInterval(function () {
num++;
cxt.clearRect(0,0,myCanvas.width,myCanvas.height);
cxt.fillRect(num,num,100,100);
},30)
}
网友评论