@@ -9,6 +9,7 @@ type Color = string;
99
1010export default class MediaProcessor {
1111 targetContext : CanvasRenderingContext2D = { } as CanvasRenderingContext2D ;
12+ targetCanvas : HTMLCanvasElement ;
1213 gapFillWith : Color = '#fff' ;
1314 mean : number [ ] = [ 0 , 0 , 0 ] ;
1415 std : number [ ] = [ 1 , 1 , 1 ] ;
@@ -18,8 +19,8 @@ export default class MediaProcessor {
1819 inputFeed : InputFeed [ ] = [ ] ;
1920
2021 constructor ( ) {
21- const targetCanvas = document . createElement ( 'canvas' ) as HTMLCanvasElement ;
22- this . targetContext = targetCanvas . getContext ( '2d' ) as CanvasRenderingContext2D ;
22+ this . targetCanvas = env . get ( 'canvas2d' ) || document . createElement ( 'canvas' ) as HTMLCanvasElement ;
23+ this . targetContext = this . targetCanvas . getContext ( '2d' ) as CanvasRenderingContext2D ;
2324 } ;
2425
2526 /**
@@ -57,7 +58,9 @@ export default class MediaProcessor {
5758 dHeight : opt . targetSize . height
5859 } ;
5960
60- if ( ! ( pixels instanceof HTMLImageElement
61+ const input = pixels ;
62+ const isImageElementLike = pixels . path && pixels . width && pixels . height ;
63+ if ( ! isImageElementLike && ! ( pixels instanceof HTMLImageElement
6164 || pixels instanceof HTMLVideoElement
6265 || pixels instanceof HTMLCanvasElement ) ) {
6366 return [ {
@@ -72,7 +75,7 @@ export default class MediaProcessor {
7275 this . pixelHeight = ( pixels as HTMLImageElement ) . naturalHeight || pixels . height ;
7376
7477 const inGPU = env . get ( 'webgl_gpu_pipeline' ) || env . get ( 'webgl_feed_process' ) ;
75- this . fitToTargetSize ( pixels , imageDataInfo , inGPU ) ;
78+ this . fitToTargetSize ( isImageElementLike ? input . path : input , imageDataInfo , inGPU ) ;
7679 data = this . getImageData ( imageDataInfo ) ;
7780 // process imageData in webgl
7881 if ( inGPU ) {
@@ -171,8 +174,8 @@ export default class MediaProcessor {
171174
172175 imageDataInfo . dWidth = canvasWidth ;
173176 imageDataInfo . dHeight = canvasHeight ;
174- this . targetContext . canvas . width = canvasWidth ;
175- this . targetContext . canvas . height = canvasHeight ;
177+ this . targetCanvas . width = canvasWidth ;
178+ this . targetCanvas . height = canvasHeight ;
176179 this . targetContext . fillStyle = imageDataInfo . gapFillWith ;
177180 this . targetContext . fillRect ( 0 , 0 , canvasHeight , canvasWidth ) ;
178181 this . targetContext . drawImage ( image , x , y , sw , sh ) ;
@@ -190,4 +193,20 @@ export default class MediaProcessor {
190193 return this . targetContext . getImageData ( dx , dy , dWidth , dHeight ) ;
191194 }
192195
196+ cover ( w , h , dw , dh ) {
197+ // 缩放后的宽高
198+ let sw = dw ;
199+ let sh = dh ;
200+ // target的长宽比大些 就把原图的高变成target那么高
201+ if ( dw / dh * h / w >= 1 ) {
202+ sw = Math . round ( sh * w / h ) ;
203+ }
204+ // target的长宽比小些 就把原图的宽变成target那么宽
205+ else {
206+ sh = Math . round ( sw * h / w ) ;
207+ }
208+
209+ const scale = [ sw / dw , sh / dh ] ;
210+ return scale ;
211+ }
193212}
0 commit comments