0

我编写了一个 JavaScript,它允许用户用鼠标在 HTML5 画布上绘图(类似于 MS Paint)。

现在,我有两个问题:

  1. 仅当 HTML5 画布元素位于网页的左上角 (0, 0) 时,绘图功能才有效,否则根本不起作用或绘图偏离中心。

  2. 我无法擦除绘图。当我擦除绘图时,它会擦除​​但一旦我再次开始绘图,它就会回来。

我的代码如下:

HTML 画布

<canvas id="can1" width="500" height="500"></canvas>1

用于画布绘图的 JavaScript

// Variables
var x1;
var y1;
var isPressed = false;
var myCanvas;
var myContext;

function startCanvas() {

    // Canvas stuff
    myCanvas = document.getElementById("can1");
    myContext = myCanvas.getContext("2d");

    // Specify a black background, and white lines that are 3 pixels thick.
    myContext.fillStyle = '#fff';
    myContext.strokeStyle = '#fff';
    myContext.fillRect(0, 0, 500, 500);
    myContext.lineWidth = 3;
    myContext.fill();
}

function functionMouseDown(e) {
    // Get coordinates
    x1 = e.clientX
    y1 = e.clientY;

    isPressed = true;
}

function functionMouseMove(e) {
    // If mouse is down and moved start drawing line
    if (isPressed == true) {
        drawLine(e);
    }
}

function functionMouseUp() {
    // Stop drawing line
    isPressed = false;
    //myContext.closePath();
    //myContext.stroke();
}

function drawLine(e) {
    // Draw line
    var x = e.clientX;
    var y = e.clientY;

    myContext.strokeStyle = '#cc0000';
    myContext.lineWidth = 1;
    myContext.moveTo(x1, y1);
    myContext.lineTo(x, y);
    myContext.stroke();

    // Set start coordinates to current coordinates
    x1 = x;
    y1 = y;
}

我用来擦除画布的 JavaScript:

myContext.clearRect(0, 0, 500, 500);
4

2 回答 2

0

我使用以下函数来完成这个

function relMouseCoords(event){/*needs fixing for general case*/
    var totalOffsetX = 0
    var totalOffsetY = 0
    var canvasX = 0
    var canvasY = 0
    var currentElement = this

    do{
        totalOffsetX += currentElement.offsetLeft
        totalOffsetY += currentElement.offsetTop
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX
    canvasY = event.pageY - totalOffsetY

    return {x:canvasX, y:canvasY}
}

HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

然后

var cord = e.target.relMouseCoords(e);
x1 = cord.x; 
y1 = cord.y;
...
var cord = e.target.relMouseCoords(e);
var x = cord.x;
var y =cord.y;

http://jsfiddle.net/mowglisanu/u3rvT/1/

于 2012-12-06T03:08:15.500 回答
0

最简单的解决方案是使用 myCanvas.offsetLeft 和 myCanvas.offsetTop 设置画布的偏移量。

于 2012-12-06T06:08:23.733 回答