簡體   English   中英

將div縮放為div,就像背景圖像一樣

[英]Scale div into div like background image

我正在開發一個Web應用程序,現在面臨一項相當棘手的任務。 我有一個圖像,我必須添加疊加。

假設我有一輛汽車的圖像。 我需要在汽車圖像上添加外部和內部溫度等值。

為這些溫度標簽添加固定像素偏移量會很容易,但圖像需要可以擴展到每個屏幕的高度和寬度。 我想不出簡單的方法將div縮放為div完全像“background-size:contain;” 適用於圖像。

在我編寫復雜的javascript縮放邏輯之前,有人能指出我正確的軌道嗎?

如果您使用SVG圖像,這將很容易: http//css-tricks.com/svg-text-typographic-designs/

以下是CSS的兩個示例:

  1. http://codepen.io/chriscoyier/pen/zxqdev
  2. http://maketea.co.uk/2013/12/16/smooth-text-overlays-with-css-transforms.html
ww = window width
wh = window height
ow = Original Width of your image
oh = Original Height of your image
nw = New Width of your image
nh = New Height of your image
mt = Margin top to adjust image to the screen vertically
ox = overlay location x coordinate according to original size of the image
oy = overlay location y coordinate according to original size of the image
nox = New ox
noy = new oy
sf = scaling factor

根據屏幕尺寸,您將擁有圖像的縮放系數。

sf = ww / ow -> we find our scaling factor
nh = oh * sf -> then calculate our new image height
mt = (oh - nh) / 2 -> amount we need to shift image up to center screen
nox = ox * sf -> new overlay x coordinate
noy = (oy * sf) - mt -> new overlay y coordinate

編輯

如果圖像太寬,則需要調整此邏輯以水平移動圖像而不是垂直移位

編輯2

如果您只針對現代瀏覽器,則可以使用CSS transform: scale(sx[, sy]); 這將按比例重新調整DIV及其所有內容的大小使用transform: scale() with transform-origin: 0 0; 從左上角重新調整大小。

我從來沒有測試過CSS3 對象 ,但我認為它對你的解決方案非常有用:

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

https://dev.opera.com/articles/css3-object-fit-object-position/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM