1

我正在使用 html 和 javascript 制作图像绘制应用程序。我用画布制作并在画布上添加了一些按钮<div>。当然,canvas 有 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;
};
4

1 回答 1

1

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

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

// 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 = "";
于 2013-06-11T02:41:25.897 回答