Rotate canvas image

1

Estpy trying to make the image on the canvas stay diagonal

This is what I have

 var imageObjCextrema = new Image()
  imageObjCextrema.onload = function() {
   ctx.drawImage(imageObjCextrema, 35, 250, 7, 50);
 }
  imageObjCextrema.src = 'img/cotaPT.png';

    
asked by Eduard 10.05.2017 в 15:25
source

2 answers

1

Rotations are usually not simple because they depend on the chosen center of rotation. All canvas has a 0.0 and by default this is on the top left. This point is the center of all rotation.

If you want to paste an image and turn it in turn, you should follow the following steps:

  • translate : transfer the 0.0 to a point that is easy to handle. The center where this image will be placed is one of them.
  • rotate : rotate the x-axis system at an angle in radians, and
  • drawImage : paste the image in the new coordinate system.

var papel = document.getElementById("papel");
var lapiz = papel.getContext("2d");

// Tracemos un rectangulo
lapiz.beginPath();
lapiz.moveTo(50,50);
lapiz.lineTo(200,50);
lapiz.lineTo(200,100);
lapiz.lineTo(50,100);
lapiz.closePath();
lapiz.stroke();

//Tomemos este rectangulo como source y copiemoslo en 130,150
var verticeX = 250;
var verticeY = 50;
var ancho = 170
var altura = 70;

lapiz.drawImage(papel, 40, 40, 170, 70, verticeX, verticeY, ancho, altura);

//Copiemos otro pero rotado alrededor del centro
//con "translate" corremos el 0,0 al centro del punto donde vamos a ubicar la imagen rotada
lapiz.translate(verticeX + ancho/2, verticeY + altura/2); 
//Usando "rotate" giramos los ejes en sentido horario en un angulo en radianes
lapiz.rotate(Math.PI/20);
//Pegamos la imagen en -ancho/2 y -altura/2 (el 0,0 es el centro de la imagen)
lapiz.drawImage(papel, 40, 40, 170, 70, -ancho/2, -altura/2, ancho, altura);
//Cada rotate genera un giro extra
lapiz.rotate(Math.PI/20);
lapiz.drawImage(papel, 40, 40, 170, 70, -ancho/2, -altura/2, ancho, altura);
lapiz.rotate(Math.PI/20);
lapiz.drawImage(papel, 40, 40, 170, 70, -ancho/2, -altura/2, ancho, altura);
<canvas id="papel" width="600" height="200">
	</canvas>
    
answered by 17.05.2017 / 04:17
source
1

Test with ctx.rotate(numeroDeRadianes) being 1 full turn 2pi radians

    
answered by 10.05.2017 в 15:41