2014-10-18 127 views
1

我在設置畫布元素的正確寬度和高度時遇到困難。獲取畫布元素的正確寬度和高度

我有一個球,只要它通過改變垂直速度來達到屏幕邊界,我就會反彈回來。它可以工作,但是一旦碰到屏幕邊緣就不會移回去,它會持續幾秒鐘,然後返回。我有這些變量來確定視域的尺寸:

var left = 0, 
    right = canvas.width, 
    top = 0, 
    bottom = canvas.height; 

如果我的球的x或y位置,這些邊界之外,速度應改爲負面的。然而,在我的動畫過程中,我將console.log設置爲x位置,到達屏幕的右邊緣時,值約爲600,這真的很奇怪,因爲我在1366x768像素的顯示器上。

此外,它不完全達到左邊的屏幕邊緣,但從它彈出50像素。

任何想法都非常感謝,因爲我一直堅持這一段時間。

這裏你可以看到一個工作示例:http://codepen.io/gbnikolov/pen/puiwk

+0

canvas.offsetHeight和canvas.offsetWidth可能工作 – 2014-10-18 10:13:07

+0

不,不幸的是他們不......你的意思是分別將它們分配給右和底部變量,對嗎? – 2014-10-18 10:25:44

回答

1

更新您的抽獎以下。

Ball.prototype.draw = function(ctx) { 
    ctx.save(); 
    // you've translated to the x and y position of the ball. 
    ctx.translate(this.x, this.y); 
    ctx.rotate(this.rotation); 
    ctx.scale(this.scaleX, this.scaleY); 
    ctx.lineWidth = this.lineWidth; 
    ctx.fillStyle = this.color; 
    ctx.strokeStyle = this.strokeColor; 
    ctx.beginPath(); 
    // Draw at 0,0 since we are already translated to the x and y. 
    ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true); 
    ctx.closePath(); 
    ctx.fill(); 
    ctx.stroke(); 
    ctx.restore(); 
} 

Live Demo

你的問題是引入的方法,您要翻譯的上下文,然後在做球的x和y的弧,所以如果你翻譯成20,20例如,然後畫20,20,你的球實際上是40,40。

+0

謝謝你,非常感謝! – 2014-10-19 10:24:02