<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Canvas拼图</title>
<style>
.canvas{border:1px solid #ddd}
</style>
<script>
var CanvasDraw = function(id,width,height){
this.element = document.getElementById(id);
this.canvas = this.element.getContext("2d");
this.element.width = width;
this.element.height = height;
this.animateArr =[];
}
CanvasDraw.prototype = {
start : function(){
var c = this.canvas;
var elt = this.element;
var isDrag = false;
c.lineWidth = 4;
c.strokeStyle = "#000";
c.lineJoin = "round";
if(navigator.userAgent.indexOf("Firefox")==-1){
c.shadowBlur = 2;
}else{
c.shadowBlur = 1;
}
c.shadowColor = "black";
elt.onmousedown = function(){
isDrag = true;
c.beginPath();
return false;
}
var g = this;
elt.onmousemove = function(evt){
if(isDrag){
var e = evt || event;
var x = e.clientX - this.offsetLeft;
var y = e.clientY - this.offsetTop + document.body.scrollTop;
c.lineTo(x,y);
c.stroke();
g.animateArr.push([x,y]); //把绘制的每一步动作都记录下来
}
}
elt.onmouseup = function(){
isDrag = false;
g.animateArr.push(-1);
}
elt.onmouseout = function(){
this.onmouseup();
}
}
}
//以动画的形式重现刚才的绘画
function animateGo(g,auto){
g.canvas.clearRect(0,0,g.element.width,g.element.height);
g.canvas.beginPath();
var loop = function(animate,i){
if(i<animate.length-1){
var arr = animate[i];
if(arr==-1){
g.canvas.beginPath();
}else{
g.canvas.lineTo(arr[0],arr[1]);
g.canvas.stroke();
}
i++;
g.timeId = setTimeout(function(){
loop(animate,i);
},10);
}
}
loop(auto || g.animateArr,0);
}
onload = function(){
var g = new CanvasDraw("musicCanvas",600,470);
g.start();
document.getElementById("btn1").onclick = function(){
animateGo(g);
}
document.getElementById("btn2").onclick = function(){
g.canvas.clearRect(0,0,g.element.width,g.element.height);
g.animateArr = [];
clearTimeout(g.timeId);
}
}
</script>
</head>
<body>
<input type="button" value="重放" id="btn1" class="c_btn"/> <input type="button" value="清空" id="btn2" class="c_btn"/><br/>
<canvas id="musicCanvas" class="canvas"></canvas>
</body>
</html>
在区域内用鼠标进行绘制,完毕后可点击重放按钮,会重现刚才绘画的过程,请在支持HTML5的浏览器下面运行