He estado luchando durante más de un día para obtener la funcionalidad de rotar selectivamente un conjunto de mosaicos que se dibujan en un lienzo en cualquier número de grados. Simplemente no lo entiendo y finalmente estoy pidiendo ayuda. Necesito poder rotar cualquier mosaico desde su punto de anclaje (arriba a la izquierda, arriba a la derecha) en cualquier grado.
El código javascript principal que me confunde es cuando determino que el mosaico debe rotarse de la siguiente manera:
function drawTile(context, tile,i) { TILE_WIDTH=tile.width; TILE_HEIGHT=tile.height; // Draw the tile with rounded corners tile_x_position=tile.x; tile_y_position=tile.y; // determine if the tile is rotated rotation_angle=tile.plot_rotate; // yes it needs rotated if (rotation_angle != 0){ radian_value=(Math.PI/180)*rotation_angle; // get center point of tile to be rotated vertical= (tile_y_position+TILE_HEIGHT)/2; horizontal= (tile_x_position+TILE_WIDTH)/2 context.translate( tile_x_position, tile_y_position); context.rotate(radian_value); // rotate the tile on its center point }Luego dibujo el azulejo.
Cuando termine, reinicié las cosas de la siguiente manera:
if (rotation_angle != 0){ context.rotate(-radian_value); context.translate( -tile_x_position, -tile_y_position); }Puede ver que no está haciendo lo que quiero que haga mirando el código javascript completo en https://jsfiddle.net/jackmstein/m69sfcrq/1/
Encontré el problema y arreglé el código en el enlace https://jsfiddle.net/jackmstein/m69sfcrq/5/
Resulta que antes de rotar el lienzo, debe especificar la referencia de traducción. Lo tenía configurado incorrectamente en el centro del mosaico en lugar de en la esquina superior izquierda.
tile_x_position=tile.x; tile_y_position=tile.y; // determine if the tile is rotated rotation_angle=tile.plot_rotate; // yes it needs rotated if (rotation_angle != 0){ radian_value=(Math.PI/180)*rotation_angle; // get left most point of tile to be rotated radian_value=(Math.PI/180)*rotation_angle; context.translate( tile_x_position, tile_y_position); //set the new point of reference for the canvas to left top context.rotate(radian_value); // rotate the tile on the new point // set the points of reference for the tile to be shown based on the rotated canvas tile_x_position=0; tile_y_position=0; }Luego, cuando haya terminado de dibujar el mosaico, restablezca el lienzo de la siguiente manera:
if (rotation_angle != 0){ context.rotate(-radian_value); //reset everything back tile_x_position=tile.x; tile_y_position=tile.y; context.translate( -tile_x_position, -tile_y_position); }