كيفية إنشاء: تحبير الصورة

تعلم كيفية إنشاء تحبير الصورة.

تحبير الصورة

شغل الفأرة فوق الصورة:

النظرة التجميلية:

تجربة بنفسك

إنشاء تحبير الصورة

الخطوة الأولى - إضافة 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:

المعineTransform يجب أن يكون نسبيًا.

* {box-sizing: border-box;}
.img-zoom-container {
  position: relative;
}
.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*ضبط حجم العدسة:*/
  width: 40px;
  height: 40px;
}
.img-zoom-result {
  border: 1px solid #d4d4d4;
  /* يتم تعيين حجم 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 = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /* يتم إدراج العدسة: */
  img.parentElement.insertBefore(lens, img);
  /* يتم حساب نسبة result DIV والعدسة: */
  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();
    /* الحصول على إحداثيات الفارص x و y: */
    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 و y: */
    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");
</script>

تجربة بنفسك