iT邦幫忙

2024 iThome 鐵人賽

DAY 3
1

ts檔不變,把縮放的功能抓出來放在directive,方便未來的應用
這裡用三種形狀展示,分別是矩形、圓形、圓角矩形
今天的內容一樣也放在 StackBlitz

首先建立ResizableDirective,在AppModule宣告

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DragDropModule } from '@angular/cdk/drag-drop'

import { AppComponent } from './app.component';
import { ResizableDirective } from './resizable.directive';
import { RotatableDirective } from './rotatable.directive';

@NgModule({
  declarations: [
    AppComponent,
    ResizableDirective,
  ],
  imports: [
    BrowserModule,
    DragDropModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

ResizableDirective

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[resizable]'
})
export class ResizableDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mousedown', ['$event'])
  onMouseDown(event: MouseEvent) {
    event.preventDefault();
    const initialWidth = this.el.nativeElement.offsetWidth;
    const initialHeight = this.el.nativeElement.offsetHeight;
    const startX = event.clientX;
    const startY = event.clientY;

    const onMouseMove = (moveEvent: MouseEvent) => {
      const newWidth = initialWidth + (moveEvent.clientX - startX);
      const newHeight = initialHeight + (moveEvent.clientY - startY);
      this.renderer.setStyle(this.el.nativeElement, 'width', `${newWidth}px`);
      this.renderer.setStyle(this.el.nativeElement, 'height', `${newHeight}px`);
    };

    const onMouseUp = () => {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };

    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  }
}

app.component.scss

.shape-container {
    display: flex;
    gap: 20px;
}
.shape {
    border: 1px solid #000;
    background-color: #f0f0f0;
}
.rectangle {
    width: 100px;
    height: 50px;
}
.circle {
    width: 100px;
    height: 100px;
    border-radius: 50%;
}
.ellipse {
    width: 150px;
    height: 100px;
    border-radius: 10px;
}

上一篇
Day2:拖曳功能:聖誕卡片
下一篇
Day4:旋轉功能
系列文
收納規劃APP32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言