@@ -32,24 +32,75 @@ export default {
3232 min : - 100 ,
3333 max : 100 ,
3434 step : 1
35+ } ,
36+ constrain : {
37+ label : "Constrain" ,
38+ type : "enum" ,
39+ default : "none" ,
40+ enum : [
41+ { label : "None (Scale)" , value : "none" } ,
42+ { label : "Contain" , value : "contain" } ,
43+ { label : "Cover" , value : "cover" }
44+ ]
3545 }
3646 } ,
3747 draw ( { canvas : { width, height } , context, props } ) {
38- const { scale, offsetX, offsetY } = props ;
48+ const { constrain, offsetX, offsetY, scale, texture } = props ;
49+
50+ if ( texture . value ) {
51+ let { width : imageWidth , height : imageHeight } = texture . value ;
52+
53+ let x ;
54+ let y ;
55+
56+ if ( constrain === "contain" ) {
57+ imageHeight = ( imageHeight / imageWidth ) * width ;
58+ imageWidth = width ;
59+
60+ y = ( height - imageHeight ) / 2 ;
61+ x = 0 ;
62+
63+ if ( imageHeight > height ) {
64+ imageWidth = ( imageWidth / imageHeight ) * height ;
65+ imageHeight = height ;
66+
67+ y = 0 ;
68+ x = ( width - imageWidth ) / 2 ;
69+ }
70+ } else if ( constrain === "cover" ) {
71+ const imageRatio = imageHeight / imageWidth ;
72+ const canvasRatio = height / width ;
73+
74+ if ( imageRatio < canvasRatio ) {
75+ imageWidth = ( width * canvasRatio ) / imageRatio ;
76+ imageHeight = height ;
77+
78+ x = ( width - imageWidth ) / 2 ;
79+ y = 0 ;
80+ } else {
81+ imageHeight = width * imageRatio ;
82+ imageWidth = width ;
83+
84+ x = 0 ;
85+ y = ( height - imageHeight * scale ) / 2 ;
86+ }
87+ } else {
88+ imageWidth = imageWidth * scale ;
89+ imageHeight = imageHeight * scale ;
90+
91+ x = ( width - imageWidth ) / 2 ;
92+ y = ( height - imageHeight ) / 2 ;
93+ }
3994
40- if ( props . texture . value ) {
41- const { width : imageWidth , height : imageHeight } = props . texture . value ;
42- const x = ( width - imageWidth * scale ) / 2 ;
43- const y = ( height - imageHeight * scale ) / 2 ;
4495 const calculatedOffsetX = ( width / 100 ) * offsetX ;
4596 const calculatedOffsetY = ( height / 100 ) * offsetY ;
4697
4798 context . drawImage (
48- props . texture . value ,
99+ texture . value ,
49100 x + calculatedOffsetX ,
50101 y + calculatedOffsetY ,
51- imageWidth * scale ,
52- imageHeight * scale
102+ imageWidth ,
103+ imageHeight
53104 ) ;
54105 }
55106 }
0 commit comments