基于zepto.js的canvas简易画图板主要实现清空画图板功能,实现撤销返回上一步功能!(各个步骤均有注释哦!)
<!DOCTYPE html>
<html>
<head>
<title>h5 demo</title>
</head>
<body>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/zepto.min.js" ></script>
</head>
<body οncοntextmenu="return false;" onselectstart="return false;" style="background:#eee;opacity: 0.1;">
<canvas id='canvas' style="margin:2px"></canvas>
<div>
<button id='c'>clear</button>
<button id="prev">返回上一步</button>
</div>
<script>
var cStep = -1;//记录步长
var histo =new Array();//存储不同阶段转化的图片
var can_height=$(window).height();
var canvas = document.getElementById('canvas');
canvas.addEventListener('touchstart',onMouseDown,false);
canvas.addEventListener('touchmove',onMouseMove,false);
canvas.addEventListener('touchend',onMouseUp,false)
canvas.height = can_height;
canvas.width = getWidth() - 25;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 255, 255, 0)';
ctx.lineWidth = 1.0; // 设置线宽
ctx.strokeStyle = "#000"; // 设置线的颜色
var flag = false;//当前是否可画图
function onMouseDown(evt)
{
evt.preventDefault();
ctx.beginPath();
var p = pos(evt);
ctx.moveTo(p.x, p.y);
flag = true;
}
function onMouseMove(evt)
{
evt.preventDefault();
if (flag)
{
var p = pos(evt);
ctx.lineTo(p.x, p.y);
ctx.lineWidth = 1.0; // 设置线宽
ctx.shadowColor = "#000";
ctx.shadowBlur = 1;
ctx.stroke();
}
}
function onMouseUp(evt)
{
evt.preventDefault();
historyPush(); //存储本次绘画
flag = false;
}
/*清除当前画布*/
var clear = document.getElementById('c');
clear.addEventListener('click',function()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
},false);
/*返回上一步*/
var prev=document.getElementById("prev");
prev.addEventListener('click',function()
{ console.log("返回上一步!");
undo();
},false);
/*返回到上一步所化内容*/
/*获取到坐标位置*/
function pos(event)
{
var x,y;
if(isTouch(event)){
x = event.touches[0].pageX;
y = event.touches[0].pageY;
}else{
x = event.layerX;
y = event.layerY;
}
return {x:x,y:y};
}
/*判断是否触摸屏幕*/
function isTouch(event)
{
var type = event.type;
if(type.indexOf('touch')>=0){
return true;
}else{
return false;
}
}
/*获取到屏幕宽度*/
function getWidth()
{
var xWidth = null;
if (window.innerWidth !== null) {
xWidth = window.innerWidth;
}
else {
xWidth = document.body.clientWidth;
}
return xWidth;
}
/*实现操作步数的存储*/
function undo()
{
if (cStep >= 0)
{
clearCanvas();
cStep--;
var tempImage = new Image();
tempImage.src = histo[cStep];
tempImage.onload = function () { ctx.drawImage(tempImage, 0, 0);};
}
}
/*操作的历史记录*/
function historyPush()
{
cStep++;
if (cStep < histo.length)
{
histo.length = cStep;
}
var value=$("#canvas").get(0).toDataURL();
//console.log(value);
histo.push(value);
}
function clearCanvas()
{
ctx.fillStyle="#FFFFFF";
var width = $("#canvas").attr("width");
var height = $("#canvas").attr("height");
ctx.fillRect(0,0,width,height);
}
</script>
</body>
</html>