How rotate only a square in Canvas html5

Hi I'm doing a practice with canvas, I want rotate only a square because when I use the method c.rotate( Degrees*Math.PI/180 ); rotate all canvas because when I move of the origin point, the square is it goes to other place.

for example I have this square in the ()enter image description here

I rotate 45 degrees the square

And I move the square the position (0,0) but It goes for other place

enter image description here

Upvotes: 1

Views: 129

Answers (2)

Case translate

case 1: //trasladar
    X = prompt("Selecciona una cordenada para trasladar X");
    Y = prompt("Selecciona una cordenada trasladar Y");
    Xreal=X*20;
    Yreal=Y*20;
    PuntoX= 400+Xreal;
    PuntoY= 200-Yreal;

      if(ban==1){
        c.clearRect(0, 0, canvas.width, canvas.height) 
        c.fillStyle="red";
        c.fillRect(PuntoX,PuntoY,40,40);
      }
      

Case rotate

  case 2:
    if(ban==1){
      c.save();
      var D = prompt("Degree");
     c.clearRect(0, 0, canvas.width, canvas.height)
       c.translate(PuntoX,PuntoY);

      c.rotate( D*Math.PI/180 );
      c.translate(-(PuntoX),-(PuntoY));
      c.fillRect(PuntoX,PuntoY,40,40);
      c.restore()

Upvotes: 0

Jean-Michel Provencher
Jean-Michel Provencher

Reputation: 735

Move the square to position (-square.width/2,-square.height/2)

Upvotes: 1

Related Questions