0

我正在通过mousedownmousemove事件记录画布上绘制的所有点。当画布调整大小时(例如,如果它是 100w x 200h,而用户将其设为 200w x 400h),我想重绘所有这些点/线,但要以新的比例。这样做的正确方法是什么?

我目前正在使用如下代码,但无法正确绘制。它画出奇怪的额外线条。

为了保存这些点,我将点记录在mousedown和中,mousemove并将一条线标记为在 中完成mouseup

调用调整大小事件:

//The new ratios
var wRatio = canvas.width / oldWidth;
var hRatio = canvas.height / oldHeight;

//We need to scale and draw all our points
for ( var i = 0, last = savedPoints.length - 1; i < last; i++ ) {
    var start = savedPoints[ i ];
    var end = savedPoints[ i + 1 ];

    //We're at a new line
    if ( start === "stopline" ) continue;

    //We're finishing a previous line
    else if ( end === "stopline" ) {
        i++;
        continue;
    }

    //Resize them
    start.x = start.x * wRatio;
    start.y = start.y * hRatio;
    end.x = end.x * wRatio;
    end.y = end.y * hRatio;

    //These lines don't make a difference
    //savedPoints[ i ] = start;
    //savedPoints[ i + 1 ] = end;

    //Start recording
    context.beginPath();

    //Move the "pen" to the point
    context.moveTo( start.x, start.y );

    //Make the connection of the "line" with our data (I draw the lines originally this way to make more "natural")
    context.quadraticCurveTo( start.x, start.y, end.x, end.y );

    //This doesn't work either
    //context.lineTo( start.x, start.y, end.x, end.y );

    //Draw the line
    context.stroke();
}
4

1 回答 1

1

我认为您的问题是您通过and对象修改savedPoints[i]AND将比率应用于每个点两次。下一次迭代, where ,将已经被修改一次。savedPoints[i+1]startendi = i+1savedPoints[i]

    //The new ratios
    var wRatio = canvas.width / oldWidth;
    var hRatio = canvas.height / oldHeight;

    //We need to scale and draw all our points
    for ( var i = 0, last = savedPoints.length - 1; i < last; i++ ) {
        var start = savedPoints[ i ];
        var end = savedPoints[ i + 1 ];
        var endx, endy, startx, starty;

        //We're at a new line
        if ( start === "stopline" ) continue;

        //We're finishing a previous line
        else if ( end === "stopline" ) {
            i++;
            continue;
        }

        //Resize them
        startx = start.x * wRatio;
        starty = start.y * hRatio;
        endx = end.x * wRatio;
        endy = end.y * hRatio;

        //Start recording
        context.beginPath();

        //Move the "pen" to the point
        context.moveTo( startx, starty );

        //Make the connection of the "line" with our data (I draw the lines originally this way to make more "natural")
        context.quadraticCurveTo( startx, starty, endx, endy );

        //This doesn't work either
        //context.lineTo( startx, starty, end.x, end.y );

        //Draw the line
        context.stroke();
    }

    for ( var i = 0, last = savedPoints.length - 1; i < last; i++ ) {
        if (savedPoints[i] !== 'stopline') {
            savedPoints[i].x *= wRatio;
            savedPoints[i].y *= hRatio;
        }
    }
于 2013-10-10T00:19:58.367 回答