获取画布元素的正确宽度和高度
问题描述:
我在设置画布元素的正确宽度和高度时遇到困难。获取画布元素的正确宽度和高度
我有一个球,只要它通过改变垂直速度来达到屏幕边界,我就会反弹回来。它可以工作,但是一旦碰到屏幕边缘就不会移回去,它会持续几秒钟,然后返回。我有这些变量来确定视域的尺寸:
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
答
更新您的抽奖以下。
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();
}
你的问题是引入的方法,您要翻译的上下文,然后在做球的x和y的弧,所以如果你翻译成20,20例如,然后画20,20,你的球实际上是40,40。
+0
谢谢你,非常感谢! – 2014-10-19 10:24:02
canvas.offsetHeight和canvas.offsetWidth可能工作 – 2014-10-18 10:13:07
不,不幸的是他们不......你的意思是分别将它们分配给右和底部变量,对吗? – 2014-10-18 10:25:44