获得画布元素的正确宽度和高度

时间:2014-10-18 10:11:34

标签: html5 canvas

我在设置canvas元素的正确宽度和高度方面遇到了困难。

我有一个球,我想通过改变它的垂直速度,每当它碰到屏幕边界时就会反弹回来。它可以工作,但不会在它碰到屏幕边缘时立即向后移动,而是持续几秒钟然后向后移动。我有这些变量来确定视口的大小:

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

如果我的球的x或y位置在这些边界之外,则速度应该变为负值。然而,在我的动画期间,我控制台。记录它的位置,当它到达屏幕的右边缘时,值大约为600,这真的很奇怪,因为我在一台1366x768px显示器上。 / p>

此外,它并没有完全到达左侧屏幕边缘,而是从它的50px反弹。

任何想法都非常感激,因为我已经坚持了很长一段时间。

您可以在此处查看一个有效的示例:http://codepen.io/gbnikolov/pen/puiwk

1 个答案:

答案 0 :(得分: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。