首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

温习canvas

2012-09-14 
复习canvas今天,项目中用到html5中的canvas,以前,在网上找到一个canvas画板的例子,以下是例子的代码:var c

复习canvas
今天,项目中用到html5中的canvas,以前,在网上找到一个canvas画板的例子,以下是例子的代码:

var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d');  var linex = new Array();  var liney = new Array();  var linen = new Array(); var defaultColor='#000';var size=0;var lastX = -1;  var lastY = -1;  var hue = 0;  var flag = 0;  function touchStart(e) {e.preventDefault();var touches = e.changedTouches,i = 0, l = touches.length, touch;for (; i < l; i++) {touch = touches[i];flag = 1;    //代表鼠标是否按下 1 按下 0释放size=linex.length;linex.push(touch.pageX-$("#canv").offset().left);  liney.push(touch.pageY-$("#canv").offset().top);  linen.push(0);  }}function touchMove(e) {e.preventDefault();var touches = e.targetTouches,i = 0, l = touches.length, touch;for (; i < l; i++) {touch = touches[i];   if (flag == 1) {     linex.push(touch.pageX-$("#canv").offset().left);     liney.push(touch.pageY-$("#canv").offset().top);     linen.push(1);     context.save();        context.translate(context.canvas.width/2, context.canvas.height/2);     context.translate(-context.canvas.width/2, -context.canvas.height/2);     context.beginPath();     context.lineWidth = 5 + Math.random() * 10;     for (var i=size;i<linex.length;i++) {   lastX = linex[i];   lastY = liney[i];   if (linen[i] == 0) {  context.moveTo(lastX,lastY);   } else {  context.lineTo(lastX,lastY);   }     }     context.strokeStyle = defaultColor;     context.shadowColor = 'white';     context.shadowBlur = 5;     context.stroke();    // context.restore();  }  }}function touchEnd(e) {var touches = e.changedTouches,i = 0, l = touches.length, touch;for (;i < l; i++) {touch = touches[i];flag = 0;  linex.push(touch.pageX-$("#canv").offset().left);  liney.push(touch.pageY-$("#canv").offset().top);  linen.push(0);}}canvas.addEventListener("touchstart", touchStart, false);canvas.addEventListener("touchmove", touchMove, false);canvas.addEventListener("touchend", touchEnd, false);


这个例子实现了以前的项目需求,但一直以来,对其不是很理解。今天重新翻出来,实现新的项目需求,再次看的时候,感觉很轻松,一看就很明了。进而感觉canvas这不错,很好玩,也不是很难。在网上,找了些教程,基本的,看看都很容易理解。在画板中,清楚里面画得痕迹,可以通过context.clearRect ( 0 , 0 , canvas.width , canvas.height )来实现。其他的感觉没有可讲,自己认真想想,慢慢体会,可能印象会更加深刻。

热点排行