某個月黑風高的夜晚,前端小白菜收到一個任務:作一張像王者榮耀登陸界面同樣的圖片。css
對面的豬八戒也太討厭了! --沉迷遊戲兩小時之後,小白菜如是說到。html
回到正題,讓咱們先上效果圖,噹噹噹:
前端
是否是看起來很簡單?其實,真的,很簡單!bash
接下來,是手摸手教學時間! ui
首先,咱們先來一張背景圖片,再放上兩隻豬,html和css代碼:url
<style>
body {
margin: 0;
}
.container {
position: relative;
width: 1080px;
height: 600px;
background: url(back.png) 100% no-repeat;
margin: 0 auto;
}
img {
height: 300px;
position: absolute;
bottom: 0;
}
.pig1 {
right: 300px;
}
.pig2 {
left: 300px;
}
</style>
<body>
<div class="container">
<div class="pig1">
<img src="1.jpg" alt="">
</div>
<div class="pig2">
<img src="2.jpg" alt="">
</div>
</div>
</body>
複製代碼
接下來的任務,就是讓這兩隻豬隨着咱們的豬蹄鼠標輕輕點擊動起來。spa
根據咱們想要獲得的圖片與鼠標之間的交互效果,爲了方便計算,以圖片的中心爲原點,創建一個座標軸。 那麼以這個座標軸爲基準,計算鼠標在圖片上滑過期的座標js爲:翻譯
$('.container').mousemove(function () {
//以圖片中心爲原點,鼠標的橫縱座標:mousex,mousey
let mousex = event.clientX - $('.container').offset().left - $('.container').width() / 2;
let mousey = event.clientY - $('.container').offset().top - $('.container').height() / 2;
})
複製代碼
說到這裏,咱們仍是沒有讓小豬動起來呀...不要着急,咱們先來了解一下css中的transform屬性。code
W3C中是這樣子介紹滴:orm
transform 屬性向元素應用 2D 或 3D 轉換。該屬性容許咱們對元素進行旋轉、縮放、移動或傾斜。
其中,咱們須要應用的語法有:
值 | 描述 |
---|---|
rotateX(angle) | 定義沿着 X 軸的 3D 旋轉。 |
rotateY(angle) | 定義沿着 Y 軸的 3D 旋轉。 |
perspective(n) | 爲 3D 轉換元素定義透視視圖。 |
matrix(a,b,c,d,e,f) | 定義 2D 轉換,使用六個值的矩陣。 |
其餘有關tranform的小技巧,能夠參考:
旋轉!縮放!移動!傾斜!走起來!
jio do ma de!有同窗舉手了:老師!那個ma什麼什麼(matrix)的是什麼呀!我不懂!
matrix,翻譯爲矩陣。那麼首先,讓咱們翻開高中數學第38頁,第二章第四小節,複習一下矩陣相關小知識。
transform
的旋轉默認是圍繞着小豬仔們的中心點座標(x,y)的,問:如何經過
transform:matrix(a,b,c,d,e,f)
中六個參數咱們能夠對小豬仔進行2D轉換?
transform:matrix(a,b,c,d,e,f)
中六個參數相對應的矩陣爲:
相應的,這六個參數對(o,o)座標的影響計算公式爲:
通過2D轉換後中心點的橫縱座標爲:
x = ax+cy+e
y = bx+dy+f
複製代碼
那麼到底怎麼用呢?
舉個栗子,咱們想讓小豬水平往左挪5px,再垂直往上挪2px,設置transform:matrix(1,0,0,1,5,2)
就能夠了。
所以,當咱們須要利用transform:matrix(a,b,c,d,e,f)
對小豬進行平面位置上對偏移操做時,只要記住:
transform:matrix(a,b,c,d,水平偏移值,垂直偏移值)
複製代碼
固然,matrix(a,b,c,d,e,f)
這個看上去==很大一坨很牛逼==的東西可不止這個小小的用法喲,rotateX()
和rotateY()
均可以用matrix(a,b,c,d,e,f)
實現。有興趣的小朋友們能夠本身去研究一下喲~
根據咱們想獲得的交互效果,在以前創建的座標軸中,rotateX()
rotateY()
值的正負以下:
let mousex,mousey,changex,changey;
let mv = 500;
$('.container').mousemove(function () {
//相對圖片中心爲座標軸,鼠標移動的位置
mousex = event.clientX - $('.container').offset().left - $('.container').width() / 2;
mousey = event.clientY - $('.container').offset().top - $('.container').height() / 2;
changex = mousey / mv;
changey = mousex / mv;
//根據鼠標移動的相對座標進行背景圖片翻轉
$('.container').css('transform', 'perspective(400px) rotatex(' + changex + 'deg) rotateY(' + changey + 'deg)')
//根據鼠標移動的對相對座標調整兩隻豬對距離
$('.pig2').css('transform', 'matrix(1,0,0,1,' + mousex / -30 + ',' + mousey / -30 + ')')
$('.pig1').css('transform', 'matrix(1,0,0,1,' + mousex / 20 + ',' + mousey / 20 + ')')
})
$('.container').mouseout(function () {
$('.container').css('transform', 'perspective(400px) rotatex(0deg) rotateY(0deg)')
$('.pig2').css('transform', 'matrix(1,0,0,1,0,0)')
$('.pig1').css('transform', 'matrix(1,0,0,1,0,0)')
})
複製代碼
好啦,如今一個有視差效果,能夠和鼠標交互的圖片已經作好啦~