首页 > 解决方案 > 以角度 6 旋转框架内的矩形图像

问题描述

我想在一个大小相同的框架内旋转一个矩形图像,如下所示:

<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) ,反之亦然,我希望在旋转期间具有相同的宽度和高度。

标签: htmlcssangular

解决方案


无需编写手动旋转图像的代码,您可以使用 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)`);
  }

推荐阅读