0

I currently have a bunch of circles that i fill with a image inside a "box", they are bouncing and colliding. Now I want them to rotate. I have tried to get this to work but I only seem to be able to rotate the entire canvas, I only want the balls to rotate.

This is my render-function:

  var img = new Image;
  img.onload = function() {
  render();
  console.log("asdsad");
  }

  img.src = "xxx.png";

  function render() {
  var ball;
  for (var i = 0; i <balls.length; i++) {
     ball = balls[i];
     ball.x = ball.nextx;
     ball.y = ball.nexty;
     context.drawImage(img, ball.x - (img.width/2), ball.y - (img.height/2));     
  }

}

GOAL: Get these balls to rotate.

EDIT: I have tried something like this, obviously I'm doing something wrong.

     context.rotate(Math.PI/180); // Should this be another value? Either way, entire canvas rotates.
     context.drawImage(img, ball.x - (img.width/2), ball.y - (img.height/2));
     //context.rotate(-Math.PI/180)
     context.restore();

balls

4

2 に答える 2

1

あなたは試したと言いました:

context.rotate(Math.PI/180);

数学で知られているように、PI = 180 度であり、PI / 180 = 1 度を実行すると、少ししか機能しません。
したがって、キャンバスを 90 度回転させたい場合は、次のように記述する必要があります。

context.rotate(Math.PI/2);

180度が必要な場合は、次のことを行う必要があります。

context.rotate(Math.PI);

そして続けます。
いくつかの計算で、必要な角度に回転させることができます。

これが機能しない場合は、この代替手段を試すことができます

この関数は引数を取り、簡単な方法でイメージを構築します。この機能はあなたを助けます

function drawImg(img, pX, pY, oX, oY, w, h, rot , context2D) {
context2D.save();
context2D.translate(pX+oX, pY+oY);
context2D.rotate(rot * Math.PI / 180);
context2D.drawImage(img, 0, 0, w, h, -(oX), -(oY), w, h);
context2D.restore();
}

概要:

img: the image object
pX: the x position of the image
pY: the y position of the image
oX: how far across the image that the origin is
oY: how far down the image that the origin is
w: width of the image
h: height of the image
rot: angle of rotation
context2D: the context that have been build from the canvas
于 2013-09-03T14:25:37.467 に答える