這邊是特殊情況,在一切都在JS 處理的階段,就把圖片置中,大小處理好的方法,
常用於image 處理後的情況。
const settings = { target : { displayHeight: 400, displayWidth: 300 } } getImageOriginalResolution = (base64) => { const image = new Image(); image.onload = () => { this.setImageResolution(image.width, image.height) this.setState((ps) => ({...ps, imgRatio: image.width / image.height})) }; image.src = base64; }; setImageResolution = (imageWidth, imageHeight) => { const {target} = this.settings; let w = (imageWidth / imageHeight) * target.displayHeight; let h = (imageHeight / imageWidth) * target.displayWidth; imageWidth / imageHeight > target.displayWidth / target.displayHeight ? h = settings.displayHeight : w = settings.displayWidth; const marginLeft = (target.displayWidth / 2) - (w * 0.5); const marginTop = (target.displayHeight / 2) - (h * 0.5); this.setState((ps) => ({...ps, imageHeight: h, imageWidth: w, imgMarginLeft: marginLeft, imgMarginTop: marginTop})) } <img style={{width: imageWidth + 'px', height: imageHeight + 'px', marginLeft: imgMarginLeft + 'px', marginTop: imgMarginTop + 'px'}}/>
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記