2013-05-14 31 views
2

我試圖在座標點x,y繪製圖像,x和y位於圖像的中心。用x,y繪製圖像與圖像的中心點有關嗎?

我有這樣的代碼,我發現前面的旋轉圖像:

function drawImageRot(img,x,y,width,height,deg) { 
    //Convert degrees to radian 
    var rad = deg * Math.PI/180; 

    //Set the origin to the center of the image 
    context.translate(x + width/2, y + height/2); 

    //Rotate the canvas around the origin 
    context.rotate(rad); 

    //draw the image 
    context.drawImage(img, width/2 * (-1), height/2 * (-1), width, height); 

    //reset the canvas 
    context.rotate(rad * (-1)); 
    context.translate((x + width/2) * (-1), (y + height/2) * (-1)); 
} 

但是它似乎借鑑下方和右側的圖像?即x,y座標是否與圖像的左上角相關?

+1

是的。在大多數框架中,(0,0)座標是容器的左上角。這對於圖像以及窗體中的控件都是如此。 – Renan 2013-05-14 14:32:58

+0

我已經添加了幾個標籤來獲得更多的知名度 - 如果我猜錯了,請更正! – 2013-05-14 14:33:11

回答

3

在該方法開始時,它將上下文從左上角轉換爲中心。 如果你想通過圖像的中心。然後你可以跳過這一步,產生下面的代碼。

function drawImageRot(img,x,y,width,height,deg) { 
    //Convert degrees to radian 
    var rad = deg * Math.PI/180; 


    //Set the origin to the center of the image 
    context.translate(x, y); 

    //Rotate the canvas around the origin 
    context.rotate(rad); 

    //draw the image 
    context.drawImage(img, width/2 * (-1), height/2 * (-1), width, height); 

    //reset the canvas 
    context.rotate(rad * (-1)); 

    // 
    context.translate((x) * (-1), (y) * (-1)); 
} 

不要忘記,您必須以與更改翻譯相同的方式撤消翻譯。

+0

如果你的意思是你不需要旋轉,那麼你也可以刪除兩個旋轉語句。 – 2013-05-14 14:39:16

+0

啊,工作,謝謝! – dan2k3k4 2013-05-14 15:20:21

1

如果你想給這個函數座標中心,而不是左上角的,只是

context.translate(x, y); 
+0

明白了,謝謝! – dan2k3k4 2013-05-14 15:20:53

0

小更換

context.translate(x + width/2, y + height/2); 

遲到了,但我覺得最簡單的移在渲染之前的圖像。

function drawBorder(img, x, y, width, height, deg){ 
    var xAdjust = width * .5, 
     yAdjust = height * .5; 
    ctx.drawImage(img, x - xAdjust, y - yAdjust, width, height); 
} 

正如你所知道的寬度和高度時,其傳遞你可以移動,其尺寸和大小的左半部分的圖像了一半。快速和骯髒,但伎倆。