Rotations are not usually easy because they depend on the chosen center of rotation. Every canvas has a 0,0 and by default it is at the top left. This point is the center of all rotation.
If you want to paste an image and which in turn is rotated, follow these steps:
translate: move 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,y axis system by an angle in radians
drawImage: Paste the image into 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);
Rotations are not usually easy because they depend on the chosen center of rotation. Every canvas has a 0,0 and by default it is at the top left. This point is the center of all rotation.
If you want to paste an image and which in turn is rotated, follow these steps:
translate
: move 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,y axis system by an angle in radiansdrawImage
: Paste the image into the new coordinate system.Try with
ctx.rotate(numeroDeRadianes)
being 1 whole turn 2pi radians