Angular前端项目添加水印
在Angular项目中添加水印可以通过自定义指令来实现。以下是一个简单的例子,演示如何创建一个水印指令:
- 首先,在你的Angular项目中创建一个新的指令。
// watermark.directive.ts
import { Directive, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
@Directive({
selector: '[appWatermark]'
})
export class WatermarkDirective implements OnInit, OnDestroy {
@Input('appWatermark') watermarkText: string;
private canvas: HTMLCanvasElement;
private context: CanvasRenderingContext2D;
private style = {
color: 'rgba(180, 180, 180, 0.3)',
fontSize: '20px',
textAlign: 'center'
};
constructor(private el: ElementRef) {}
ngOnInit(): void {
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.drawWatermark();
this.setWatermark();
}
ngOnDestroy(): void {
this.removeWatermark();
}
private drawWatermark(): void {
const { width, height } = this.el.nativeElement;
this.canvas.width = width;
this.canvas.height = height;
this.context.fillStyle = this.style.color;
this.context.font = this.style.fontSize;
this.context.textAlign = this.style.textAlign;
this.context.translate(0.5, 0.5); // for crispier lines
const textWidth = this.context.measureText(this.watermarkText).width;
const x = (width - textWidth) / 2;
const y = (height - parseInt(this.style.fontSize)) / 2;
this.context.fillText(this.watermarkText, x, y);
}
private setWatermark(): void {
this.el.nativeElement.style.backgroundImage = `url('${this.canvas.toDataURL('image/png')}')`;
this.el.nativeElement.style.backgroundRepeat = 'no-repeat';
this.el.nativeElement.style.backgroundSize = '100% 100%';
this.el.nativeElement.style.backgroundPosition = 'center center';
}
private removeWatermark(): void {
this.el.nativeElement.style.backgroundImage = 'none';
}
}
- 在你的Angular模块中声明这个指令:
// app.module.ts
import { WatermarkDirective } from './watermark.directive';
@NgModule({
declarations: [
WatermarkDirective
],
// ...
})
export class AppModule { }
- 在你的Angular组件模板中使用这个指令:
<!-- your.component.html -->
<div appWatermark="Your Watermark Text">
<!-- Your content here -->
</div>
确保你的元素有足够的宽度和高度,以便水印可以适当地渲染和显示。这个指令会在该元素上设置背景图像作为水印,并在组件销毁时清除水印。
评论已关闭