使用javascript在画布中旋转图像后缩放图像

时间:2015-02-04 21:43:41

标签: javascript image canvas rotation

请告诉我我做错了什么。我想用java脚本在画布上制作图像编辑器。一切都按我想要的方式工作,除非我第一次旋转而不是尝试缩放图像。

我想让它像在Photoshop中旋转和缩放图像一样工作,但是当你在旋转它们后尝试缩放时,我的图像会在x和y轴上稍微移动。

这是我的代码jsfidle

的示例
function scale(){

    var dx = mouse_curent_x - mouse_start_x;
    var dy = mouse_curent_y - mouse_start_y;



        if(img.scale_direction == "right"){
            img.width += dx;
        }
        if(img.scale_direction == "left"){
            img.width += -dx;
            img.left += dx;
        }
        if(img.scale_direction == "bottom"){
            img.height += dy;
        }
        if(img.scale_direction == "top"){
            img.height += -dy;
            img.top += dy;
        }
        if(img.scale_direction == "top-left"){
            img.height += -dy;
            img.top += dy;
            img.width += -dx;
            img.left += dx; 
        }
        if(img.scale_direction == "top-right"){
            img.height += -dy;
            img.top += dy;
            img.width += dx;
        }
        if(img.scale_direction == "bottom-right"){
            img.height += dy;
            img.width += dx;
        }
        if(img.scale_direction == "bottom-left"){
            img.height += dy;
            img.width += -dx;
            img.left += dx;             
        }


    mouse_start_x = mouse_curent_x;
    mouse_start_y = mouse_curent_y;

    draw(true, true)
}

function rotate(){

    var imageCenterX = img.left+(img.width/2);
    var imageCenterY = img.top+(img.height/2);

    var a = { x: mouse_curent_x, y: mouse_curent_y };
    var b = { x: imageCenterX, y: imageCenterY };
    var c = { x: mouse_start_x, y: mouse_start_y };

    var dir = ccw(a, b, c);

    var radians = getAngle(a, b, c);
    var cursor = dir == -1 ? getAngle(a, b, {x: b.x+1, y: b.y}) : getAngle(a, b, {x: b.x+1, y: b.y})+Math.PI;

    img.angle = dir == -1 ? -radians + img.old_angle : radians + img.old_angle;

    draw(true, true)
}


function draw(withAnchors, withSelection){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();

    // Rotate
    var tX = img.left + img.width/2;
    var tY = img.top + img.height/2;
    ctx.translate(tX, tY);

    ctx.rotate(img.angle);

    // ctx.scale(img.scale_width, img.scale_height);

    ctx.drawImage(img, -img.width/2, -img.height/2, img.width, img.height);
    ctx.restore();

    if(withSelection) drawSelection();
    if(withAnchors) drawDragAnchor();
}

在jsfiddle示例中,您可以通过单击蓝色矩形来旋转图像,然后单击粉红色矩形来缩放图像。

0 个答案:

没有答案