如何创建:图像缩放

学习如何创建图像缩放。

图像缩放

请将鼠标悬停在图像上:

放大预览:

亲自试一试

创建图像缩放

第一步 - 添加 HTML:

<div class="img-zoom-container">
  <img id="myimage" src="img_girl.jpg" width="300" height="240" alt="Girl">
  <div id="myresult" class="img-zoom-result"></div>
</div>

第二步 - 添加 CSS:

容器必须具有“相对”定位。

* {box-sizing: border-box;}
.img-zoom-container {
  position: relative;
}
.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*set the size of the lens:*/
  width: 40px;
  height: 40px;
}
.img-zoom-result {
  border: 1px solid #d4d4d4;
  /*set the size of the result div:*/
  width: 300px;
  height: 300px;
}

ਤੀਜਾ ਪਗਲਾ - JavaScript ਜੋੜੋ:

function imageZoom(imgID, resultID) {
  var img, lens, result, cx, cy;
  img = document.getElementById(imgID);
  result = document.getElementById(resultID);
  /* lens ਬਣਾਓ: */
  lens = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /* lens ਨੂੰ ਜੋੜੋ: */
  img.parentElement.insertBefore(lens, img);
  /* result DIV ਅਤੇ lens ਦਰਮਿਆਨ ਪ੍ਰਪੋਰਸ਼ਨ ਕੈਲਕੂਲੇਟ ਕਰੋ: */
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  /* result DIV ਲਈ ਬੈਕਗਰਾਊਂਡ ਪ੍ਰਤੀਯੋਗਿਤਾ ਸੈੱਟ ਕਰੋ: */
  result.style.backgroundImage = "url('" + img.src + "')";
  result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
  /* ਜਦੋਂ ਕੋਈ ਪਾਇਨਟਰ ਚਿੱਤਰ ਜਾਂ ਲੈਂਸ 'ਤੇ ਲਿਆਉਂਦਾ ਹੈ ਤਾਂ ਇਸ ਫੰਕਸ਼ਨ ਨੂੰ ਚਲਾਓ: */
  lens.addEventListener("mousemove", moveLens);
  img.addEventListener("mousemove", moveLens);
  /* ਸਾਥੇ ਵੀ ਟੱਚ ਸਕ੍ਰੀਨ ਲਈ ਲਾਗੂ: */
  lens.addEventListener("touchmove", moveLens);
  img.addEventListener("touchmove", moveLens);
  function moveLens(e) {}}
    var pos, x, y;
    /* ਚਿੱਤਰ 'ਤੇ ਹੋਣ ਵਾਲੀ ਗਤੀ ਨੂੰ ਰੋਕੋ: */
    e.preventDefault();
    /* ਸ਼ਾਨਦਾਰ ਪਾਠ ਦੇ ਸਥਾਨਾਂ ਨੂੰ ਹੱਲ ਕਰੋ: */
    pos = getCursorPos(e);
    /* ਲੈਂਸ ਦਾ ਸਥਾਨ ਹੱਲ ਕਰੋ: */
    x = pos.x - (lens.offsetWidth / 2);
    y = pos.y - (lens.offsetHeight / 2);
    /* ਲੈਂਸ ਨੂੰ ਚਿੱਤਰ ਤੋਂ ਬਾਹਰ ਨਾ ਲਿਆਓ: */
    if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
    if (x < 0) {x = 0;}
    if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
    if (y < 0) {y = 0;}
    /* ਲੈਂਸ ਦਾ ਸਥਾਨ ਸੈਟ ਕਰੋ: */
    lens.style.left = x + "px";
    lens.style.top = y + "px";
    /* ਲੈਂਸ ਵਿੱਚ ਦੇਖੇ ਗਏ ਚਿੱਤਰ ਦਿਸਾਓ: */
    result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
  }
  function getCursorPos(e) {
    var a, x = 0, y = 0;
    e = e || window.event;
    /* ਚਿੱਤਰ ਦੇ x ਅਤੇ y ਸਥਾਨ ਪ੍ਰਾਪਤ ਕਰੋ: */
    a = img.getBoundingClientRect();
    /* ਸ਼ਾਨਦਾਰ ਪਾਠ ਦੇ ਸਥਾਨਾਂ ਨੂੰ ਹੱਲ ਕਰੋ: */
    x = e.pageX - a.left;
    y = e.pageY - a.top;
    /* ਕਿਸੇ ਪੰਨੇ ਸਰਕਣ ਨੂੰ ਧਿਆਨ ਵਿੱਚ ਰੱਖੋ: */
    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {x : x, y : y};
  }
}

ਚੌਥਾ ਪੜਾਅ - ਵਿਸਥਾਰ ਪ੍ਰਭਾਵ ਚੇਨਾਲਾ ਕਰੋ:

<script>
imageZoom("myimage", "myresult");

亲自试一试