下面这段代码使页面闪烁严重,问题在哪里?怎么改进呢?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=unicode" />
<title>Rect</title>
<style type="text/css">
</style>
<script type="text/javascript">
var Rect =
{
obj: null,
container: null,
init: function(containerId)
{
Rect.container = document.getElementById(containerId);
if(Rect.container)
{
Rect.container.onmousedown = Rect.start;
}
else
{
alert('You should specify a valid container!');
}
},
start: function(e)
{
var o = Rect.obj = document.createElement('div');
o.style.position = "absolute";
o.style.left = o.mouseBeginX = Rect.getEvent(e).x;
o.style.top = o.mouseBeginY = Rect.getEvent(e).y;
o.style.height = 0;
o.style.width = 0;
o.style.border = "dotted black 1px";
var deleteLink = document.createElement('a');
deleteLink.href="#";
deleteLink.onclick = function()
{
Rect.container.removeChild(this.parentNode);
}
deleteLink.innerText = "x";
o.appendChild(deleteLink);
Rect.container.appendChild(o);
Rect.container.onmousemove = Rect.move;
Rect.container.onmouseup = Rect.end;
},
move: function(e)
{
var o = Rect.obj;
var dx = Rect.getEvent(e).x - o.mouseBeginX;
var dy = Rect.getEvent(e).y - o.mouseBeginY;
if(dx<0)
{
o.style.left = Rect.getEvent(e).x;
}
if(dy<0)
{
o.style.top = Rect.getEvent(e).y;
}
o.style.height = Math.abs(dy);
o.style.width = Math.abs(dx);
},
end: function(e)
{
Rect.container.onmousemove = null;
Rect.container.onmouseup = null;
Rect.obj = null;
},
getEvent: function(e)
{
if (typeof e == 'undefined')
{
e = window.event;
}
if(typeof e.x == 'undefined')
{
e.x = e.layerX;
}
if(typeof e.y == 'undefined')
{
e.y = e.layerY;
}
return e;
}
};
</script>
</head>
<body>
<div id="main" style="border: solid red 1px; height:90%; width:60%; curssor: default;">
<canvas id = "myCanvas" width = "800px" height = "500px"></canvas>
</div>
增加一个按钮,可以关闭绘画效果,用来配合测试删除功能
<input type="button" value="停止绘画" id="t"/>
</body>
<script type="text/javascript">
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");