如何在画布中旋转所选元素

时间:2016-11-02 00:38:42

标签: javascript html canvas

所以我正在尝试在画布中构建一个小图像编辑器,目前我有按钮,onclick将特定图像绘制到画布(buildLayers())然后我可以选择画布上的任何图像,我可以移动它周围。我的下一步是添加旋转,但仅限于所选图像。当前旋转的图像会出现,但原始的图像也会出现...另一个问题是我无法选择旋转的图像,当我拖动原始图像时,当我将原件向右移动时,旋转的图像会转到不同的方向,旋转向下移动。

function renderCanvas() {
    requestAnimationFrame(renderCanvas);

    g.clearRect(0, 0, canvas.width, canvas.height);
    g2.clearRect(0, 0, canvas.width, canvas.height);
    
    for (var i = 0; i < numOfImages; i++) {
        drawImg(imgX[i], imgY[i], images[i]);
    }
    //draw a border on selected image
    if (numOfImages > 0) {
        drawBorder(imgX[selectedImg], imgY[selectedImg]);
        rotareImage(imgX[selectedImg], imgY[selectedImg], images[selectedImg]);
    }


}
// -------------------------------------------------------------------

function drawImg(x, y, images) { 
    g.drawImage(images, x - (imgWidth / 2), y - (imgHeight / 2), imgWidth, imgHeight);
}

function buildLayers() {
    for (var layer = 0; layer < numOfImages + 1; layer++) {
        imgX[layer + numOfImages] = canvas.width / 2;
        imgY[layer + numOfImages] = canvas.height / 2;
    }
}
function rotareImage(x, y, images) {
    
    g.save();
    
    g.translate(canvas.width / 2, canvas.height / 2);
    g.rotate(Math.radians(90));
    g.translate(-canvas.width / 2, -canvas.height / 2);

    drawImg(x, y, images);
    g.restore();
    
}

Math.radians = function (degrees) {
    return degrees * Math.PI / 180;
};

1 个答案:

答案 0 :(得分:0)

您只需要旋转单个图像而不是整个画布,并且必须在调用drawImg()之前执行此操作。

renderCanvas 函数中:

for (var i = 0; i < numOfImages; i++) {

    // If this image is to be rotated/bordered
    // it needs to be done now, before drawImg() is called,
    // on the layer, not on the entire canvas
    if(i===selectedImg){

        // Draw the border
        drawBorder(imgX[i], imgY[i]);

        // Overwrite the Image object with the rotated version
        imgX[i] = rotateLayer(imgX[i], 90); // 90 degree rotation
    }

    // Now add it to the canvas
    drawImg(imgX[i], imgY[i], images[i]);
}

然后创建一个rotateLayer函数,该函数将使用无头画布旋转图像,然后返回Image对象。

function rotateLayer(img, degrees){

    // Create a headless canvas
    var c = document.createElement("canvas");
    c.width = img.width; c.height = img.height;
    var ctx = c.getContext("2d");

    // Draw the image and rotate it on the headless canvas
    ctx.drawImage(img, 0, 0);
    ctx.rotate(Math.radians(degrees));

    // Get the rotated image back from the headless canvas
    var image = new Image();
    image.src = c.toDataURL();

    return image;
}

请参阅评论中的代码说明。

免责声明:我刚刚在答案框中写了这个并没有测试它。如果你只是复制和粘贴它可能会或可能不会工作,它旨在告诉你如何做,而不是为你做。