最近研究了一个大牛的程序,用canvas终于做出来了一个小的鼠标屏幕画线程序
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>鼠标画线</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var isIE = (document.all) ? true : false;
var $ = function (id) {
return "string" == typeof id ? document.getElementById(id) : id;
};
var Class = {
create: function() {
return function() { this.initialize.apply(this, arguments); }
}
}
var Extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
}
var Bind = function(object, fun) {
return function() {
return fun.apply(object, arguments);
}
}
var BindAsEventListener = function(object, fun) {
return function(event) {
return fun.call(object, (event || window.event));
}
}
function addEventHandler(oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = fnHandler;
}
};
function removeEventHandler(oTarget, sEventType, fnHandler) {
if (oTarget.removeEventListener) {
oTarget.removeEventListener(sEventType, fnHandler, false);
} else if (oTarget.detachEvent) {
oTarget.detachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = null;
}
};
//拖放程序
var SimpleDrag = Class.create();
SimpleDrag.prototype = {
//拖放对象,触发对象
initialize: function(drag) {
this.Drag = $(drag);
this._x = this._y = 0;
this._fM = BindAsEventListener(this, this.Move);
this._fS = Bind(this, this.Stop);
this.Drag.style.position = "absolute";
addEventHandler(this.Drag, "mousedown", BindAsEventListener(this, this.Start));
},
//准备拖动
Start: function(oEvent) {
cxt.moveTo(oEvent.clientX,oEvent.clientY);
addEventHandler(document, "mousemove", this._fM);
addEventHandler(document, "mouseup", this._fS);
},
//拖动
Move: function(oEvent) {
if(oEvent.button == 0){
cxt.lineTo(oEvent.clientX,oEvent.clientY);
cxt.stroke();
cxt.moveTo(oEvent.clientX,oEvent.clientY);
}
},
//停止拖动
Stop: function() {
removeEventHandler(document, "mousemove", this._fM);
removeEventHandler(document, "mouseup", this._fS);
}
};
</script>
<script>
new SimpleDrag("myCanvas");
</script>
</body>
</html>