我正在使用 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;
};