自由绘制直线

时间:2012-04-19 15:17:52

标签: html5 canvas

我已经开始开发一个用于在2d创建房间的画布应用程序。我想用这样的免费绘图创建一个房间:

http://soud.se/images/room.JPG

示例:devfiles.myopera.com/articles/649/example2.html(无法创建超过2个超链接)

当房间的自由绘图完成并释放鼠标按钮时(或按下按钮时),我希望程序自动生成一个直线的房间,如下所示:

http://soud.se/images/room1.JPG

我只想要有90度角的房间,所以我想知道是否有办法做到这一点。

//安德烈亚斯

1 个答案:

答案 0 :(得分:0)

<强> Live Demo

这是一种方法。我使用2个画布对象,你在顶部绘制“绘画”,一旦你释放鼠标,它就会从你的线的起点到终点绘制一条直线。还有改进的余地,但我只想提出一个解决方案。

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    drawCanvas = document.getElementById("drawCanvas"),
    drawCtx = drawCanvas.getContext("2d"),
    painting = false,
    lastX = 0,
    lastY = 0,
    startX = 0,
    startY = 0,
    lineThickness = 1;

canvas.width = canvas.height = 600;

drawCanvas.width = drawCanvas.height = 600;

drawCanvas.onmousedown = function(e) {
    painting = true;
    drawCtx.fillStyle = "#000";
    lastX = e.pageX - this.offsetLeft;
    lastY = e.pageY - this.offsetTop;
    startX = lastX;
    startY = lastY;
};

drawCanvas.onmouseup = function(e){
    painting = false;
    var x2 = e.pageX - this.offsetLeft,
        y2 = e.pageY - this.offsetTop;

    ctx.strokeStyle = "#000";
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(x2, y2);
    ctx.stroke();

    drawCtx.clearRect(0, 0, 600, 600);
}

drawCanvas.onmousemove = function(e) {
    if (painting) {
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;

        // find all points between        
        var x1 = mouseX,
            x2 = lastX,
            y1 = mouseY,
            y2 = lastY;


        var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
        if (steep){
            var x = x1;
            x1 = y1;
            y1 = x;

            var y = y2;
            y2 = x2;
            x2 = y;
        }
        if (x1 > x2) {
            var x = x1;
            x1 = x2;
            x2 = x;

            var y = y1;
            y1 = y2;
            y2 = y;
        }

        var dx = x2 - x1,
            dy = Math.abs(y2 - y1),
            error = 0,
            de = dy / dx,
            yStep = -1,
            y = y1;

        if (y1 < y2) {
            yStep = 1;
        }


        for (var x = x1; x < x2; x++) {
            if (steep) {
                drawCtx.fillRect(y, x, lineThickness , lineThickness );
            } else {
                drawCtx.fillRect(x, y, lineThickness , lineThickness );
            }

            error += de;
            if (error >= 0.5) {
                y += yStep;
                error -= 1.0;
            }
        }



        lastX = mouseX;
        lastY = mouseY;

    }
}
​