<!DOCTYPE html>
<html>
<head>
<base href="." />
<script type="text/javascript" charset="utf-8">
window.AngularVersionForThisPlunker = 'latest'
</script>
<title>angular playground</title>
<link rel="stylesheet" href="style.css" />
<script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js/dist/zone.js"></script>
<script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
<script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
<script src="config.js"></script>
<script>
System.import('app')
.catch(console.error.bind(console));
</script>
</head>
<body>
<my-app>
loading...
</my-app>
</body>
</html>
/* Styles go here */
https://github.com/leye0/AngularSignatureComponent
# Angular Signature Component
Minimalist signature component for Angular
## Getting Started
Copy signature.component.ts in your project (and add it to the declaration of your module-s).
Tweak for your needs.
### Usage
```html
<!-- This is a place where the signature pad should be used. -->
<!-- The signature canvas will fill the whole space. In the example, full width and a height of 100px. -->
<!-- Notice how in the example the style reacts to the state of the component. -->
<div [ngStyle]="{'border': myAwesomeSignaturePad.isFocused ? '1px solid gray' : 'none'}" style="width: 100%; height: 100px;">
<!-- When calling "save", the $event received from the component output is your image as a default data URL as PNG -->
<app-signature (savedSignatureAsDataUrl)="someServiceThatHandlesTheData($event)" #myAwesomeSignaturePad></app-signature>
</div>
<!-- There are two functions: clear and save. -->
<button (click)="myAwesomeSignaturePad.clear()">Clear</button>
<button (click)="myAwesomeSignaturePad.save()">Save</button>
```
var angularVersion;
if(window.AngularVersionForThisPlunker === 'latest'){
angularVersion = ''; //picks up latest
}
else {
angularVersion = '@' + window.AngularVersionForThisPlunker;
}
System.config({
//use typescript for compilation
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
'npm:': 'https://unpkg.com/'
},
//map tells the System loader where to look for things
map: {
'app': './src',
'@angular/core': 'npm:@angular/core'+ angularVersion + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + angularVersion + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + angularVersion + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + angularVersion +'/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms' + angularVersion + '/bundles/forms.umd.js',
'@angular/animations': 'npm:@angular/animations' + angularVersion + '/bundles/animations.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + angularVersion + '/bundles/animations-browser.umd.js',
'@angular/core/testing': 'npm:@angular/core' + angularVersion + '/bundles/core-testing.umd.js',
'@angular/common/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-testing.umd.js',
'@angular/common/http/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-http-testing.umd.js',
'@angular/compiler/testing': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler-testing.umd.js',
'@angular/platform-browser/testing': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-testing.umd.js',
'@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic-testing.umd.js',
'@angular/http/testing': 'npm:@angular/http' + angularVersion + '/bundles/http-testing.umd.js',
'@angular/router/testing': 'npm:@angular/router' + angularVersion + '/bundles/router-testing.umd.js',
'tslib': 'npm:tslib@1.6.1',
'rxjs': 'npm:rxjs',
'typescript': 'npm:typescript@2.2.1/lib/typescript.js'
},
//packages defines our app package
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
});
//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';
platformBrowserDynamic().bootstrapModule(AppModule)
//our root app component
import {Component, NgModule, VERSION} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {SignatureComponent} from './signature.component'
@Component({
selector: 'my-app',
template: `
<div>
<h1>Angular Signature Component</h1>
<h2>https://github.com/leye0/AngularSignatureComponent</h2>
<!-- This is a place where the signature pad should be used. -->
<!-- The signature canvas will fill the whole space. In the example, full width and a height of 100px. -->
<div style="border: 1px solid gray; width: 100%; height: 100px;">
<!-- When calling "save", the $event received from the component output is your image as a default data URL as PNG -->
<app-signature (savedSignatureAsDataUrl)="someFunctionThatHandlesTheData($event)" #myAwesomeSignaturePad></app-signature>
</div>
<!-- There are two functions: clear and save. -->
<button (click)="myAwesomeSignaturePad.clear()">Clear</button>
<button (click)="myAwesomeSignaturePad.save()">Save</button><br />
<br/><br/>
<h3>This is how your data looks like once saved</h3>
<input style="width: 100%" id="text-signature" type="text" />
<br/><br/>
<h3>This is how your image will be saved</h3>
<img id="img-signature" />
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
someFunctionThatHandlesTheData($event): void {
console.log($event);
document.querySelector('#text-signature').value = $event;
document.querySelector('#img-signature').src = $event;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, SignatureComponent ],
bootstrap: [ App ]
})
export class AppModule {}
import { Component, OnInit, ViewChild, HostListener, EventEmitter, ElementRef, Output } from '@angular/core';
@Component({
selector: 'app-signature',
template: '<canvas #canvas></canvas>',
styles: ['signature.component.scss']
})
export class SignatureComponent implements OnInit {
@ViewChild('canvas') canvasElementRef: ElementRef;
segments: Segment[] = [];
@Output() savedSignatureAsDataUrl: EventEmitter<string> = new EventEmitter<string>();
get canClear(): boolean { return this.segments.length > 0; }
private get canvas(): HTMLCanvasElement { return this.canvasElementRef.nativeElement; }
private get context(): CanvasRenderingContext2D { return this.canvas.getContext("2d"); }
private isTouchingDown: boolean;
private isTouchingInside: boolean;
private previousUserSelectStyle: string;
@HostListener("window:resize", ["$event"])
onWindowResize = ($event: UIEvent) => this.resizeCanvas()
@HostListener("document:mousedown", ["$event"])
@HostListener("document:mousemove", ["$event"])
@HostListener("document:touchstart", ["$event"])
@HostListener("document:touchmove", ["$event"])
touchOutside = ($event: MouseEvent) => this.handleTouchOutside($event, false)
@HostListener("document:click", ["$event"])
@HostListener("document:mouseup", ["$event"])
@HostListener("document:touchend", ["$event"])
touchUpOutside = ($event: MouseEvent) => this.handleTouchOutside($event, true)
@HostListener("document:scroll", ["$event"]) onDocumentScroll =
($event: MouseEvent) => {
if (this.isTouchingInside) {
$event.preventDefault();
}
}
@HostListener("document:wheel", ["$event"]) onDocumentWheel =
($event: MouseWheelEvent) => {
if (this.isTouchingInside) {
$event.preventDefault();
}
}
@HostListener("touchstart", ["$event"])
ontouchstart = ($event: TouchEvent) => this.drawDown($event, true)
@HostListener("touchmove", ["$event"])
ontouchmove = ($event: TouchEvent) => this.drawMove($event, true)
@HostListener("touchend", ["$event"])
ontoucheend = ($event: TouchEvent) => this.drawEnd()
@HostListener("mousedown", ["$event"])
onmousedown = ($event: MouseEvent) => this.drawDown($event, false)
@HostListener("mousemove", ["$event"])
onmousemove = ($event: MouseEvent) => this.drawMove($event, false)
@HostListener("mouseup", ["$event"])
onmouseup = ($event: MouseEvent) => this.drawEnd()
constructor(private element: ElementRef) {}
ngOnInit(): void {
this.previousUserSelectStyle = (document.body as HTMLElement).style.userSelect;
this.resizeCanvas();
this.clear();
this.element.nativeElement.style.background = 'white';
}
private resizeCanvas(): void {
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
this.canvas.width = this.canvas.offsetWidth;
this.canvas.height = this.canvas.offsetHeight;
this.refreshCanvas();
}
private drawDown($event: any, isTouch: boolean): void {
const touchLocationEvent: TouchLocationEvent = isTouch ? $event.touches[0] : $event;
const point: Point = this.getTouchLocation(touchLocationEvent);
(document.body as HTMLElement).style.userSelect = 'none';
this.isTouchingDown = true;
this.segments.push({ points: [point] });
this.refreshCanvas();
}
private drawMove($event: any, isTouch: boolean): void {
if (!this.isTouchingDown) { return; }
const touchLocationEvent: TouchLocationEvent = isTouch ? $event.touches[0] : $event;
const point: Point = this.getTouchLocation(touchLocationEvent);
this.segments[this.segments.length - 1].points.push(point);
this.refreshCanvas();
}
private drawEnd(): void {
this.isTouchingDown = false;
(document.body as HTMLElement).style.userSelect = this.previousUserSelectStyle;
}
private handleTouchOutside($event: any, up: boolean): boolean {
const focused: boolean = this.canvas.contains($event.target as Node);
this.isTouchingInside = focused;
if (!focused && up) {
this.drawEnd();
}
return !focused;
}
save(): void {
this.savedSignatureAsDataUrl.emit(this.canvas.toDataURL());
}
clear(): void {
this.segments = [];
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
private refreshCanvas(): void {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.beginPath();
this.segments.filter(s => s.points.length).forEach(s => {
this.context.moveTo(s.points[0].x, s.points[0].y);
s.points.forEach(p => this.context.lineTo(p.x, p.y));
});
this.context.stroke();
}
private getTouchLocation(touchLocation: TouchLocationEvent): Point {
const rect: ClientRect = this.canvas.getBoundingClientRect();
return {
x: touchLocation.clientX - rect.left,
y: touchLocation.clientY - rect.top
};
}
}
export interface TouchLocationEvent {
clientX: number;
clientY: number;
}
export interface Point {
x: number;
y: number;
}
export interface Segment {
points: Point[];
}