I can't clear the canvas?


B

Bill.Connelly

If you run this script, it's pretty obvious what I'm trying to do. You
click, and drag, and a line is drawn from where you clicked to where
you are. After each time a line is drawn from the origin to where the
mouse is now, previous lines are erased. Hence giving the illusion of
one line following your cursor (nothing amazing here).

The problem is that the lines aren't being deleted (except for between
clicks)

What am I doing wrong?

Thanks.

<html>
<head>

<script type="application/x-javascript">

document.onmousedown = drawline;
document.onmousemove = moveline;
document.onmouseup = endline;

var isDragging=false;
var startX, startY

function drawline(e) {
startX=e.clientX; //set the start X-Y for the line
startY=e.clientY;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(startX,startY); //move the start of the line to the
initial click point
isDragging=true; //confirm the mouse is down for dragging.
return false;
}

function moveline(e) {
if(!isDragging) return; //if the mouse is not being held
down, do nothing
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.globalCompositeOperation = 'source-over';
ctx.moveTo(startX,startY); //move the start of the line to
the initial click point
ctx.lineTo(e.clientX,e.clientY); //draw the line to where the mouse
is now
ctx.clearRect(0,0,300,300); //clear any previous lines
ctx.stroke(); //draw the new line
return false;
}

function endline() {
isDragging=false; //the mouse is no longer held down
return false;
}
</script>


</head>
<body>
<canvas id="canvas" width="300" height="300"
style="position:absolute;top:0px;left:0px;"></canvas>
</body>
</html>
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top