coldmund
coldmund

Reputation: 155

How can I keep the canvas in focus

I'm making an image drawing application with html and javascript. I made it with canvas and added some buttons(<div>s) on the canvas. Of course, canvas have onmousedown, onmouseup, onmousemove handlers to draw lines. But when I move mouse to the position of buttons or out of the canvas, then return to the canvas area, line breaks. refer to the code(http://jsfiddle.net/coldmund/MQKMv/) please.

html:

<div>
    <div style="position: absolute; margin-top: 0px; margin-left: 0px;"><canvas id="canvas" width="500" height="300" onmousedown="down(event)" onmouseup="up()" onmousemove="move(event)" style="border: 1px solid"></canvas></div>
    <div style="position: absolute; margin-top: 100px; margin-left: 100px; width: 100px; height: 100px; background: #ff0000; opacity: 0.5"></div>
</div>

js:

var mouseDown = false;
down = function(e)
{
    mouseDown = true;
    prevX = e.clientX;
    prevY = e.clientY;
};

up = function()
{
    mouseDown = false;
};

move = function(e)
{
    if( mouseDown === false )
        return;

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.lineWidth = 5;
    context.lineCap = 'round';

    context.beginPath();
    context.moveTo( prevX, prevY );
    context.lineTo( e.clientX, e.clientY );
    context.stroke();

    prevX = e.clientX;
    prevY = e.clientY;
};

Upvotes: 1

Views: 414

Answers (1)

veritasetratio
veritasetratio

Reputation: 611

Here is a fiddle with a potential solution (fiddle). This basically toggles the buttons css property to pointer-events:none while drawing on the canvas.

The differences between your code and mine basically reduce to the following:

// CSS
.no-pointer-events {
    pointer-events:none;
}

// Inside the mousedown handler
document.getElementById( "button1" ).class = "no-pointer-events";

// Inside the mouseup handler
document.getElementById( "button1" ).class = "";

Upvotes: 1

Related Questions