本文同时发布到 我的个人博客站点
之前做的一个项目中有一个需求,要让用户在手机上签名并保留笔迹。我的第一反应是,这个用 js 应该能够实现,于是 Google 之,还真让我找到了signature_pad;更加让人高兴的是,Github 上有位老兄把它封装成了 Angular Module angular2-signaturepad,看来是不用重复造轮子了。
使用 angular2-signaturepad
安装
在 Ionic 项目下执行如下命令:
npm install angular2-signaturepad --save
关键代码
// import into app module
import { SignaturePadModule } from 'angular2-signaturepad';
...
@NgModule({
declarations: [ ],
imports: [ SignaturePadModule ],
providers: [ ],
bootstrap: [ AppComponent ]
})
// then import for use in a component
import { Component, ViewChild } from 'angular2/core';
import { SignaturePad } from 'angular2-signaturepad/signature-pad';
@Component({
template: '<signature-pad [options]="signaturePadOptions" (onBeginEvent)="drawStart()" (onEndEvent)="drawComplete()"></signature-pad>'
})
export class SignaturePadPage{
@ViewChild(SignaturePad) signaturePad: SignaturePad;
private signaturePadOptions: Object = { // passed through to szimek/signature_pad constructor
'minWidth': 5,
'canvasWidth': 500,
'canvasHeight': 300
};
constructor() {
// no-op
}
ngAfterViewInit() {
// this.signaturePad is now available
this.signaturePad.set('minWidth', 5); // set szimek/signature_pad options at runtime
this.signaturePad.clear(); // invoke functions from szimek/signature_pad API
}
drawComplete() {
// will be notified of szimek/signature_pad's onEnd event
console.log(this.signaturePad.toDataURL());
}
drawStart() {
// will be notified of szimek/signature_pad's onBegin event
console.log('begin drawing');
}
}
示例代码
我写了一份示例代码,请参考这里
网友评论
(float or function) Radius of a single dot.
minWidth
(float) Minimum width of a line. Defaults to 0.5.
maxWidth
(float) Maximum width of a line. Defaults to 2.5.
throttle
(integer) Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.
backgroundColor
(string) Color used to clear the background. Can be any color format accepted by context.fillStyle. Defaults to "rgba(0,0,0,0)" (transparent black). Use a non-transparent color e.g. "rgb(255,255,255)" (opaque white) if you'd like to save signatures as JPEG images.
penColor
(string) Color used to draw the lines. Can be any color format accepted by context.fillStyle. Defaults to "black".
velocityFilterWeight
(float) Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.
onBegin
(function) Callback when stroke begin.
onEnd
(function) Callback when stroke end.
这些就是参数项