在角度6的框架内旋转矩形图像

时间:2018-11-12 09:42:06

标签: html css angular

我想在具有相同尺寸的框架内旋转矩形图像:

<div style="border:1px solid #d3d3d3;width:208px;height:250px">
 <img style="width:208px;height:250px" src="https://www.webslake.com/w_img/t_i/lpw.png" [style.transform]="styles"> </div>

   <button type="button" class="btn btn-undo btn-lg" (click)="rotateImage('left')">

和旋转图像的按钮:

rotateImage(direction) {    
    if (direction === 'left') {
      this.rotationAmount = this.rotationAmount + -90;
    } else if(direction === 'right') {
      this.rotationAmount = this.rotationAmount + 90;
    }
    this.styles =  'rotate(' + this.rotationAmount + 'deg)';

  }

如何在div框架内进行旋转而不更改宽度和高度,因为如果我旋转(new)width = old(height),反之亦然,我希望在旋转过程中具有相同的宽度和高度。

2 个答案:

答案 0 :(得分:0)

我添加了逻辑来计算样式的顶部和左侧:

rotateImage(direction: string) {

 if (direction === 'left') {
   let flag = this.width;
   this.width = this.height;
   this.height = flag;
   this.rotationAmount = this.rotationAmount + -90;
   if (this.rotationAmount == -360) {
    this.rotationAmount = 0;
   }
  console.log(this.rotationAmount);
   if (this.rotationAmount === -180 || this.rotationAmount === 0) {
     this.top = 0;
     this.left = 0;
   } else {
     this.top = (this.width-this.height)/2 * (-1); 
     this.left = (this.width-this.height)/2;
     console.log(this.top, this.left)
   }
} 

 else if(direction === 'right') {
   this.rotationAmount = this.rotationAmount + 90;
 }
 this.styles =  'rotate(' + this.rotationAmount + 'deg)';
}

它是stackblitz https://stackblitz.com/edit/angular-gz9zqs?embed=1&file=src/app/app.component.ts

的链接

答案 1 :(得分:0)

您可以使用Renderer2(这是Angular功能),而不是编写用于手动旋转图像的代码。

   <button type="button" class="btn btn-undo btn-lg imagepreview" (click)="rotateImage('left')">
   <button type="button" class="btn btn-undo btn-lg imagepreview" (click)="rotateImage('right')">

在TS文件中,

import {Renderer2} from '@angular/core';

在构造函数中添加它,

private renderer: Renderer2

添加此方法

rotateImage(direction) {
    this.angle += direction == 'left' ? -90 : 90;
    this.renderer.setStyle(document.querySelector('.imagepreview'), 'transform', `rotate(${this.angle}deg)`);
  }