2014-04-05 19 views
1

我正在玩HTML5畫布,我遇到了一些奇怪的行爲。我正在做基於以下三個步驟的基礎動畫:爲什麼數字在畫布上顯得扭曲?

  1. 我調用內部的update()函數,以便更改對象的x和y。
  2. 我用這行代碼清除畫布this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  3. 我重繪了所有的元素。

我這是怎麼得出的數字:

// drawing a circle 
function drawCircle(x,y) { 
    var rad = 5; 
    ctx.beginPath(); 
    ctx.arc(x, y, rad, 0, 2 * Math.PI); 
    ctx.closePath(); 
    ctx.fill(); 
} 

// and a rect 
function drawRect(x, y,) { 
    var width = 60, 
     height = 10; 
    ctx.fillRect(x, y, width, height); 
} 

現在,我希望我的矩形設置爲60像素的寬度和高度10px的。我在<canvas>標籤後面添加了一個div,並將其寬度和高度分別設置爲60px和10px,以便說明差異。正如你可以看到的圖片,顯然我的矩形不是60х10。這同樣適用於這個圈子。我在這裏錯過了什麼? enter image description here

here是小提琴

+0

請添加小提琴。根據我的經驗,你還必須添加'canvas.attr('width')= 60; canvas.attr('height')= 10;'。這似乎解決了我的問題。 – Anubhav

+0

你的''風格如何? –

+0

@PaulS。 #game_field { width:500px; height:500px; 邊框:1px純黑色; } – dKab

回答

2

設置畫布的使用它的尺寸是寬度和高度屬性(標記)或屬性(在JS):

<canvas id="..." width=400 height=400></canvas> 

在JS:

canvasEl.width = 400; 
canvasEl.height = 400; 

請勿使用CSS,因爲這隻會影響畫布元素但不是它的位圖(將畫布視爲圖像)。畫布的默認大小爲300 x 150像素。如果你不改變這個尺寸,它會被拉伸到你使用CSS設置的尺寸。這就是爲什麼我們一般不推薦使用CSS(有些情況下雖然有些特殊情況,例如打印情況,非1:1像素寬高比等等CSS)。

1

也許這是因爲你的風格你的畫布與/高度costum。一個畫布的默認寬度/高度是150 * 300,如果你不能很好地縮放,你會得到如你所見的結果。

drawImage(image, x, y, width, height) 
    This adds the width and height parameters, which indicate the size to which to 
    scale the image when drawing it onto the canvas. 

所以要簡短,你必須縮放你的圖紙。

the Canvas element on MDN

Canvas drawing on MDN