Forum Moderators: open

Message Too Old, No Replies

My Etch-a-sketch

I made one, but it slows down.

         

adni18

12:44 am on Dec 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here is my script for an "etch-a-sketch". It works, but in IE, it slows down after the first few pixels. Why, and how can this be prevented?

<div id="drawspot" style="height:500"></div>
<script language=javascript>
var dir="right";
var a=20;
var b=20;
function addDot(l,t)
{
document.all.drawspot.innerHTML+="<span style=\"background:black\;position:absolute\;left:"+a+"px\;top:"+b+"px\;margin:0px\;padding:0px\;font-size:1px\;width:1px\;height:1px\"></span>";
if(dir=="right")
{
a++;
}
if(dir=="left")
{
a--;
}
if(dir=="down")
{
b++;
}
if(dir=="up")
{
b--;
}
}
function cd(dirr)
{
dir=dirr;
}
window.setInterval("addDot()",1);
</script>

<a href="#" onClick="cd('right')">Right</a> ¦ <a href="#" onClick="cd('left')">Left</a> ¦ <a href="#" onClick="cd('up')">Up</a> ¦ <a href="#" onClick="cd('down')">Down</a>

Bernard Marx

1:29 am on Dec 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Simply that it's one whole loada innerHTML to write, and to handle.
To cut down on the 'inner' code, the styling could be done in a stylesheet. I've used one that uses a contextual selector so the SPAN doesn't need a className.

I had a go with DOM element creation methods, but it too will slow down.
I think it needs to be done another way - using one div per line.

<html><head><title>DrawSpot</title>
<style>
#drawspot span
{
background: black;
position: absolute;
font-size: 1px;
width: 5px;
height: 5px;
}
</style>
<script language="javascript">
var drn="right";
var x=20;
var y=20;
var k=0

function addDot()
{
var dot = document.createElement('span');
dot.style.left = x + 'px';
dot.style.top = y + 'px';
document.getElementById('drawspot').appendChild(dot);

switch(drn)
{
case "right": x++; break;
case "left" : x--; break;
case "down" : y++; break;
case "up" : y--; break;
}
}

timer = window.setInterval("addDot()",30);

</script>

</head>
<body>
<div id="drawspot" style="height:500"></div>

<a href="#" onClick="cd('right')">Right</a> ¦
<a href="#" onClick="cd('left')">Left</a> ¦
<a href="#" onClick="cd('up')">Up</a> ¦
<a href="#" onClick="cd('down')">Down</a>
</body>
</html>

adni18

3:25 am on Dec 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That doesn't work for me. It doesn't draw the lines.

Bernard Marx

2:23 pm on Dec 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It does for me.
Remember that scripts pasted from WebmasterWorld often need some slight rearrangement. For instance, because I missed out a semi-colon after the last global var assignment at the top (var k=0;), the script doesn't work when pasted on one line. It needs reorganising into the formatting as seen on the page.