如何保持画布的焦点

时间:2013-06-11 01:48:45

标签: javascript html5 canvas

我正在用html和javascript制作一个图像绘制应用程序。我用画布制作它并在画布上添加了一些按钮(<div> s)。当然,帆布有onmousedown,onmouseup,onmousemove处理程序来绘制线条。但是当我将鼠标移动到按钮位置或画布外,然后返回画布区域,换行。 请参阅代码(http://jsfiddle.net/coldmund/MQKMv/)。

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;
};

1 个答案:

答案 0 :(得分:1)

这是一个潜在解决方案的小提琴(fiddle)。在绘制画布时,这基本上将按钮css属性切换为pointer-events:none

您的代码和我的代码之间的差异基本上减少到以下几点:

// 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 = "";