复习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);