HTML5 Canvas 学习之二

View Code
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
body {
    margin:0;
    overflow:hidden;
}
</style>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
onload = function() {
    //获取面板对象
    var canvas = document.getElementById("canvas");
    //获取CANVAS2D花板对象
    var context = canvas.getContext('2d');
context.fillStyle   = '#00f';        //填充颜色
context.strokeStyle = 'black';        //线的颜色
context.lineWidth   = 2;                    //线的宽度
context.beginPath();                        //开始
// Start from the top-left point.
context.moveTo(0, 0);                         //笔放在哪个点
context.lineTo(0,$("#canvas").height());        //连接线
context.lineTo($("#canvas").width(),$("#canvas").height());
context.moveTo($("#canvas").width(), $("#canvas").height());     //把笔离纸,重新设置坐标
context.lineTo($("#canvas").width(),0);
context.lineTo(0,0);
// Done! Now fill the shape, and draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
//context.fill();                        //填充所画的内容
context.stroke();                    //将所画的画出来
context.closePath();


var clickX = new Array(),clickY=new Array(),clickDrag = new Array(),canDraw = false ;


$('#canvas').mousemove(function(e){  
    if(canDraw){
        //鼠标在页面在X坐标  这个容器的左边距
        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);  
        redraw();  
    }
})

$('#canvas').mousedown(function(e){  
    //是否正在画图
  canDraw = true;  
  addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);  
  redraw();  
})
$('#canvas').mouseup(function(e){ 
    canDraw=false;
})

function addClick(x,y,dragging){
    //添加到数组里面
    clickX.push(x);  
      clickY.push(y);  
      clickDrag.push(dragging);
}
//画图方法
function redraw(){  
  for(var i=0; i < clickX.length; i++)  
  {  
    context.beginPath();  
    if(clickDrag[i] && i){//当是拖动而且i!=0时,从上一个点开始画线。  
      context.moveTo(clickX[i-1], clickY[i-1]);  
     }else{  
       context.moveTo(clickX[i]-1, clickY[i]);  
     }  
     context.lineTo(clickX[i], clickY[i]);  
     context.closePath();  
     context.stroke();  
  }  
}  


}
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="1000">your browser don't support html canvas!</canvas>
</body>
</html>

转载于:https://www.cnblogs.com/-gap/archive/2012/06/08/2542213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值