初学javascript,希望和大家交流。
首先创建一个canvas
<canvas id="myCanvas" class="myCanvas" οnmοusemοve="draw();" οnmοusedοwn="pMoveTo();" οnmοuseup="cancel();"></canvas>
<script src="js/jquery-1.5.2.min.js"></script>
<script>
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var cx = $('#myCanvas').offset().left;
var cy = $('#myCanvas').offset().top;
//初始化画板
var init = function(){
for(var x = 0.5 ; x < 500 ;x += 10){
cxt.moveTo(x,0);
cxt.lineTo(x,500);
}
for(var y = 0.5 ; y < 500 ;y += 10){
cxt.moveTo(0,y);
cxt.lineTo(500,y);
}
cxt.strokeStyle="#eee";
cxt.stroke();
}
init();
//上下文环境,用于记录鼠标的轨迹
var drawContext = function(x,y){
var end_x = 0;
var end_y = 0;
return function(x,y){
cxt.lineTo(x,y);
cxt.stroke();
end_x = x;
end_y = y;
cxt.moveTo(end_x,end_y);
}
}
var dc;
//每一次落笔(鼠标单击)都创建一个上下文环境
function pMoveTo(e){
e=e||window.event;
var _x = e.clientX - cx;
var _y = e.clientY - cy;
cxt.moveTo(_x,_y);
cxt.beginPath();
cxt.strokeStyle="red";
dc = drawContext(_x,_y);
}
//画画
function draw(e){
e=e||window.event;
var _x = e.clientX - cx;
var _y = e.clientY - cy;
if(dc){
dc(_x,_y);
}
}
//鼠标放开,则释放这次落笔
function cancel(){
if(dc){
dc = null;
}
else{
return;
}
}