【问题标题】:How can I keep the canvas in focus如何使画布保持焦点
【发布时间】:2013-06-11 10:41:25
【问题描述】:

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

【问题讨论】:

    标签: javascript html canvas


    【解决方案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 = "";
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2019-09-19
      • 2012-05-12
      相关资源
      最近更新 更多