1. 程式人生 > >css3實現3d焦點圖

css3實現3d焦點圖

css3實現3d焦點圖

之前寫的焦點圖的基礎上新增3d效果
要點:1、perspective新增透視效果
2、計算滑鼠位置

   <div class="border-3d-wrap">
        <div class="wrap" onclick="test()">
            <img src="../img/1.png" alt="" id='bannerImg'>
        </div>
    </div>
.border-3d-wrap {
    width: 730px;
    height
: 336px
; margin: 0 auto; perspective: 300; /* 新增在需要透視元素的父級 */ -webkit-perspective: 500;/* chrome 使用perspective: 300px;或-webkit-perspective: 300; */ }
.wrap{ transition: transform .1s ease-in-out; } #bannerImg { display: block; width: 730px; height: 336px; transition: opacity 1s ease-in-out
; }
const threeDWrap = document.getElementsByClassName("border-3d-wrap")[0]
        const imgWrap = document.getElementsByClassName("wrap")[0]
        const wrapX = threeDWrap.offsetLeft
        const wrapY = threeDWrap.offsetTop
        const wrapWidth = threeDWrap.offsetWidth
        const wrapHeight = threeDWrap.offsetHeight
        const
wrapWidthHalf = threeDWrap.offsetWidth / 2 const wrapHeightHalf = threeDWrap.offsetHeight / 2 function animation3D(ev) { Ev= ev || window.event; const pointX = Ev.clientX//獲取滑鼠位置 const pointY = Ev.clientY const signX= Math.abs(pointX - wrapX) / (pointX - wrapX) const signY= Math.abs(pointY - wrapY) / (pointY - wrapY) let shadowOffsetLeft = rotateX = shadowOffsetTop = rotateY = -100 if ((pointX - wrapX) >=0 && (pointX - wrapX) <= wrapWidth && (pointY - wrapY) >=0 && (pointY - wrapY) <= wrapHeight){//滑鼠位置在焦點圖內時觸發 shadowOffsetLeft = (pointX - wrapX - wrapWidthHalf) / wrapWidthHalf * -10 rotateY = (pointX - wrapX - wrapWidthHalf) / wrapWidthHalf * 1 shadowOffsetTop = (pointY - wrapY - wrapHeightHalf) / wrapHeightHalf * 10 rotateX = (pointY - wrapY - wrapHeightHalf) / wrapHeightHalf * -1 } imgWrap.style.boxShadow = `${shadowOffsetLeft === -100 ? 0 : shadowOffsetLeft}px ${shadowOffsetTop === -100 ? 0 : shadowOffsetTop}px 50px 0 #888` imgWrap.style.transform = `rotate3d(${rotateX === -100 ? 0 : rotateX}, ${rotateY === -100 ? 0 : rotateY}, 0, 2deg)` } document.onmousemove = animation3D;