繁体   English   中英

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

[英]How to rotate selected element in 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; }; 

您需要仅旋转单个图像而不是整个画布,并且必须在drawImg()之前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;
}

请参阅注释中的代码说明。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM