0

Having problems with restoring the background in a canvas. I have a canvas that changes size depending on what the options say (and it can get very big), I draw images all over it, and now I want an indicator to show where the mouse is in a grid like format. The problem is that the red box gets drawn, but the background doesn't get redrawn next time the curX or curY is changed.

One odd part I notice is that when I take the mouse to a black area, the red box seems to be a dark red, but when I move back and forth over the same spot, the red seems to get stronger. And sometimes the red boxes I drew before also get stronger without revisiting these areas, like a trail is forming.

Only sometimes does the background return, but that is usually when I leave the area.

<canvas id="leveldraw" onmousemove="getMouse(event)" onmouseout="stopMouse()" width="0" height="0"></canvas>

...

var oldBlk = null;
...
function getMouse(e)
{
    var offsetpos = recursive_offset(canvas);
    var oldX = curX;
    var oldY = curY;
    mouseX = e.clientX + offsetpos.x + (canvas.offsetLeft/2);
    mouseY = e.clientY + offsetpos.y + (canvas.offsetTop/2)+24;
    curX = Math.floor(mouseX/24);
    curY = Math.floor(mouseY/24);
    if(oldX!=curX || oldY!=curY)
    {
        if(oldBlk != null)
            ctx.putImageData(oldBlk,(oldX*24)-24,(oldY*24)-24);
        oldBlk = ctx.getImageData((curX*24)-24,(curY*24)-24,72,72);
        ctx.lineWidth="1";
        ctx.strokeStyle="red";
        ctx.rect(curX*24,curY*24,24,24);
        ctx.stroke();
    }
}
function stopMouse()
{
    ctx.putImageData(oldBlk,(curX*24)-24,(curY*24)-24);
    oldBlk = null;
}

recursive_offset(): Get mouse position in scrollable div

I've even tried getImageData on the whole canvas, but that didn't seem to work. Possibly it did restore the whole background when leaving the canvas, BUT the red boxes came back once I returned to the canvas.

Community
  • 1
  • 1
Edward
  • 302
  • 1
  • 3
  • 15

1 Answers1

1

You should use ctx.beginPath() before you're next drawing operation. Calling stroke() or fill() doesn't clear the stack and will get drawn again next time which is causing the trail to form.

MacroMan
  • 1,821
  • 21
  • 30