簡體   English   中英

通過 javascript 旋轉圖像

[英]Rotating image via javascript

我正在嘗試使用 javascript 旋轉圖像,它應該很簡單,但我不知道如何在 canvas 上的特定坐標處繪制旋轉圖像。 這是我找到並嘗試使用的代碼:

ctx.save();  
    // Translate to the center point of our image  
    ctx.translate(selectedImg.width * 0.5, selectedImg.height * 0.5);  
    // Perform the rotation  
    ctx.rotate( rotAngle * 0.01745 );  
    // Translate back to the top left of our image  
    ctx.translate(-selectedImg.width * 0.5, -selectedImg.height * 0.5);  
    // Finally we draw the image  
    ctx.drawImage(selectedImg, 0, 0);  
    // And restore the context ready for the next loop  
    ctx.restore();  

它只是旋轉左上角的圖像。 我怎樣才能繪制圖像讓我們說右下角?

正如MSDN上所記錄的那樣。 function drawImage 具有三個簽名。

void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

其中d代表目的地,s代表來源。

這里的解決方案應該是計算圖像分辨率和 canvas 分辨率,並確保將圖像放在 canvas 內,然后計算我們應該繪制圖像的 x、y 軸。

ctx.save();
// Translate to the center point of our image  
ctx.translate(selectedImg.width * 0.5, selectedImg.height * 0.5);
// Perform the rotation  
ctx.rotate(rotAngle * 0.01745);
// Translate back to the top left of our image  
ctx.translate(-selectedImg.width * 0.5, -selectedImg.height * 0.5);
// Finally we calculate the destination and draw the image 

var selectedImgWidth  = selectedImg.width;
var selectedImgHeight = selectedImg.height;

var xOffset = selectedImgWidth < canvas.width ? (canvas.width - selectedImgWidth) : 0;
var yOffset = selectedImgHeight < canvas.height ? (canvas.height - selectedImgHeight) : 0;

ctx.drawImage(selectedImg, xOffset, yOffset);

// instead of ctx.drawImage(selectedImg, 0, 0);  
// And restore the context ready for the next loop  
ctx.restore();

我希望能解決你的問題。

編輯 1: Chenged 目的地目標

這個 function 對我有用:

CanvasRenderingContext2D.prototype.drawImageRotated = function (img,x,y,angle)
{

this.save();  


var cposX = x + img.width / 2;
var cposY = y + img.height / 2;



this.translate(cposX,cposY); // move canvas center

this.rotate(degToRad(angle));

this.translate(-cposX,-cposY);


this.drawImage(img, x, y);


this.restore();
    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM