0

我正在研究这个小绘图应用程序类型的东西,但它在 Firefox 中不起作用。不过,它在 chrome 中运行良好。这是javascript,然后我在HTML中有一个常规的旧画布元素。任何帮助表示赞赏!

/* FOR THE DRAWING APPLICATION */
/* =========================== */

var canvasMouse, contextMouse;

var started = false;
var x, y;

function initMouse() {

    // Get the drawing canvas
    canvasMouse = document.getElementById('drawing');
    contextMouse = canvasMouse.getContext('2d');

    // Add some event listeners so we can figure out what's happening
    // and run a few functions when they are executed.
    canvasMouse.addEventListener('mousemove', mousemovement, false);
    canvasMouse.addEventListener('mousedown', mouseclick, false);
    canvasMouse.addEventListener('mouseup', mouseunclick, false);

}

function mouseclick() {
    // When the mouse is clicked. Change started to true and move
    // the initial position to the position of the mouse
    contextMouse.beginPath();
    contextMouse.moveTo(x, y);
    started = true;

}
function mousemovement(e) {

    // Get moust position
    x = e.offsetX;
    y = e.offsetY;

    // If started is true, then draw a line
    if(started) {

        contextMouse.lineTo(x, y);
        contextMouse.stroke();

    }

}

function mouseunclick() {
    // Change started to false when the user unclicks the mouse
    if(started) {
        started = false;    
    }

}

有任何想法吗?

4

1 回答 1

0

offsetX并且offsetY在 Firefox 中不受支持(请参阅此处的兼容性表)。相反,您需要使用layerXand layerY

以下将在 Firefox 中工作(见fiddle):

/* FOR THE DRAWING APPLICATION */
/* =========================== */

var canvasMouse, contextMouse;

var started = false;
var x, y;

function initMouse() {

    // Get the drawing canvas
    canvasMouse = document.getElementById('drawing');
    contextMouse = canvasMouse.getContext('2d');

    // Add some event listeners so we can figure out what's happening
    // and run a few functions when they are executed.
    canvasMouse.addEventListener('mousemove', mousemovement, false);
    canvasMouse.addEventListener('mousedown', mouseclick, false);
    canvasMouse.addEventListener('mouseup', mouseunclick, false);

}

function mouseclick(e) {
    // When the mouse is clicked. Change started to true and move
    // the initial position to the position of the mouse

    // Get moust position
    x = e.layerX;
    y = e.layerY;

    console.log("coords", x, y);

    contextMouse.beginPath();
    contextMouse.moveTo(x, y);
    started = true;

}
function mousemovement(e) {

    // Get mouset position
    x = e.layerX;
    y = e.layerY;

    console.log("coords", x, y);

    // If started is true, then draw a line
    if(started) {               
        contextMouse.lineTo(x, y);
        contextMouse.stroke();

    }

}

function mouseunclick() {
    // Change started to false when the user unclicks the mouse
    if(started) {
        started = false;    
    }

}

initMouse();

如果您想避免浏览器特定的条件代码和/或您的画布元素在 DOM 层次结构中偏移(请阅读上面链接的兼容性表中 layerX 和 layerY 的限制),可能存在使用 jQuery 及其position()方法的论据。

于 2012-05-15T00:57:16.840 回答