html画布鼠标后面的一行

时间:2013-12-12 09:15:38

标签: javascript canvas html5-canvas

所以我想跟随鼠标做一条线,然后点击绘制该线,我需要这个来绘制多边形。我的想法是每次鼠标移动时绘制一条线但是它会弄乱很多线条,所以我决定在鼠标移动后用白线画出旧线条来清理,这样就只有一条线路可以移动从最后点击的点到当前的鼠标位置。My jsFiddle for this.但它不能按照我想要的方式工作,我在点击时绘制多边形,但鼠标后面没有线,所以我无法看到哪一行在画画。我不知道哪里错了?也许有一些我没有找到的现成解决方案?我的代码:

    var polygonX = [];
    var polygonY = [];
    var lineReady = 0;
    var whileLineX;
    var whiteLineY;

    $("#body").bind('mousemove', function (ev) {
        if (lineReady >= 2) {

        var context;
        //clear old lines
        if (whiteLineX !== null && whiteLineY !== null) {
            context = $("#canvas")[0].getContext('2d');
            context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
            context.lineTo(whiteLineX, whiteLineY);
            context.strokeStyle = '#ffffff';
            context.stroke();
        }
        //draw a new line
        context = $("#canvas")[0].getContext('2d');
        var offset = $('#body').offset();
        var x = ev.clientX - offset.left;
        var y = ev.clientY - offset.top;

        context.beginPath();
        context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
        context.strokeStyle = '#000000';
        context.lineTo(x, y);
        context.stroke();

        whileLineX = x;
        whiteLineY = y;

    }
});


    $("#body").bind('click', function (ev) {

        var offset = $('#body').offset();
        var x = ev.clientX - offset.left;
        var y = ev.clientY - offset.top;

        polygonX

.push(x);
    polygonY.push(y);

    lineReady++;
    if (lineReady >= 2) {

        var context = $("#canvas")[0].getContext('2d');

        context.beginPath();
        context.moveTo(polygonX[lineReady - 2], polygonY[lineReady - 2]);
        context.lineTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
        context.stroke();

    }

});`

1 个答案:

答案 0 :(得分:2)

执行此操作的最佳方法是使用一些动画。

每次绘制一条线时,将其坐标(第一点和最后一点)推入数组中。然后在每个动画循环中绘制数组(查看this link,它将向您解释如何设置动画) 。然后你会想要从数组的最后一行的最后一个点画一条线,比如说红色,你将线条推到鼠标位置。

这样做可以让你随时跟随鼠标一条红线,让你“预览”一条线。

Algo-wise它看起来像:

var arrayOflines = [];

canvas.onclick -> 
     var coordinates = mouseposition()
     arrayOfLines.push(coordinates)

function mouseposition(){
   returns x and y of your mouse on the canvas
}

function draw(array){
    loop through array
    draw line from array[0] to array[1], then from array[1] to array[2] on canvas
}

function drawPreview(){
    draw line from last point of arrayOflines to mouseposition;
}

//so here we are:
function animationloop{

   erase your canvas

   draw(arrayOfLines);  //draw your array
   drawPreview(); //draw your 'preview' line

   requestAnimationFrame(animationloop); //animate 
}

以这种方式做事将使您获得干净的结果。

相关问题