html画布鼠标后的一行

html canvas a line following mouse

本文关键字:一行 鼠标 布鼠标 html      更新时间:2024-07-01

所以我想在鼠标后面画一条线,点击绘制这条线,我需要它来绘制多边形。我的想法是每次鼠标移动时都画一条线,但这会把很多线弄得一团糟,所以我决定在鼠标移动后用白线来清理旧线,这样从上次点击的点到当前鼠标位置只有一条线。我的jsFiddle。但它并没有按照我想要的方式工作,是的,我在点击时画多边形,但鼠标后面没有线,所以我看不到我画的是哪条线。我不知道哪里出了问题?也许有一些现成的解决方案我没有找到?Mycode:

    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();
    }
});`

最好的方法是使用一些动画。

每次绘制一条线时,都要将其坐标(第一个点和最后一个点)推到数组中。然后在每个动画循环处绘制数组(查看此链接,它将解释如何制作动画)。然后,您需要从数组最后一行的最后一点开始绘制一条线,比如说用红色绘制的线,将线推到鼠标位置。

这样做可以让你在鼠标后面始终有一条红线,让你可以"预览"一条线。

Algo明智的做法是:

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 
}

这样做会让你获得一个干净的结果。