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>