Browse Source

NseBackgroundImage

Corentin NELHOMME 1 year ago
parent
commit
7154202564
2 changed files with 118 additions and 6 deletions
  1. 2 6
      index.html
  2. 116 0
      index.js

+ 2 - 6
index.html

@@ -238,7 +238,7 @@
   margin-right: 32px;">
 
       <img class="imageeditor" style="position: absolute;
-      height: 100%;
+      height: 100%; 
       width: 100%;
       object-fit: cover;
       object-position: center top;" src="https://onehealth-dev.livinweb.fr/assets/websiteFiles/cache/image-cache/websiteFiles/images/RG_img/tronquee-anais-temoignage-img-20250417-wa0001.5caa399d.webp" alt="">
@@ -369,7 +369,7 @@
 
     <div style="height: 200vh;">
 
-      <section id="section_RG_topBannerImage15641" class="pagehead bgimageeditor hidden lg:block h-[32rem] lg:py-12 lg:px-12 bg-white text-black bg-cover bg-center lg:text-white text-center relative" style="background-image: url('https://onehealth-dev.livinweb.fr/assets/websiteFiles/cache/image-cache/websiteFiles/images/RG_img/j-agis-pour-une-vie-saine-v5-lw.1981c32b.webp');background-position-y: 38%;" data-resourceid="15641">
+      <section id="section_RG_topBannerImage15641" class="pagehead bgimageeditor block h-[32rem] lg:py-12 lg:px-12 bg-white text-black bg-center lg:text-white text-center relative" style="background-image: url('https://picsum.photos/1000/1000');" data-resourceid="15641">
         <div class="absolute bottom-0 left-0 right-0 pb-12 flex flex-col items-center">
 
 <h2 class="text-accessibility px-8 lg:px-0 mt-8 lg:mt-0"><p id="siteeditor-longtitle-15641-rte" href="/rest/newsiteeditor/longtitle/15641" field="longtitle" method="PUT" class="siteeditor " data-resourceid="15641" data-successmsg="Modification effectuée" data-data="{&quot;longtitle&quot;:&quot;J’agis pour une vie saine&quot;,&quot;syncsite&quot;:1}">J’agis pour une vie saine</p></h2>
@@ -378,10 +378,6 @@
 
 </section>
 
-
-
-
-
     </div>  </body>
   <script defer src="./index.js" type="module"></script>
 </html>

+ 116 - 0
index.js

@@ -863,6 +863,121 @@ let NEWSITEEDITOR = (function () {
   }
   //Fin du nseImageEditor
 
+  //nseBgImageEditor
+  //nseBgImageEditor
+  function nseBgImageEditor() {
+    const elems = document.querySelectorAll(".bgimageeditor");
+
+    elems.forEach((elem) => {
+      // 1) Extraction de l'URL du background
+      elem.addEventListener(
+        "click",
+        (e) => {
+          elem.style.borderTop = "10px solid red";
+          elem.style.borderBottom = "10px solid red";
+
+          const bg = getComputedStyle(elem).backgroundImage; // ex: 'url("…/votre-image.jpg")'
+          const urlMatch = bg.match(/url\(["']?(.*?)["']?\)/);
+          if (!urlMatch) return; // pas d'image → on skip
+          const imgUrl = urlMatch[1];
+
+          // 2) Chargement de l'image pour lire sa taille naturelle
+          const img = new Image();
+          let Iw, Ih;
+          img.onload = () => {
+            Iw = img.naturalWidth;
+            Ih = img.naturalHeight;
+            elem.style.backgroundSize = "cover";
+          };
+          img.src = imgUrl;
+
+          // 3) Variables de drag
+          let isDragging = false;
+          let startX, startY;
+          let origX = 0,
+            origY = 0;
+
+          //Gestion du zoom
+          let zoom = 1;
+          const zoomStep = 0.05;
+          const minZoom = 0.5;
+          const maxZoom = 3;
+
+          // Récupérer la pos courante (px → nombre)
+          function getBgPos() {
+            const [x, y] = getComputedStyle(elem).backgroundPosition.split(" ");
+            return [parseFloat(x) || 0, parseFloat(y) || 0];
+          }
+
+          function calculateBackgroundSize(zoom, size, elem) {
+            elem.style.backgroundSize = zoom * size + "px";
+            console.log(zoom * size);
+          }
+
+          elem.addEventListener("mousedown", (e) => {
+            e.preventDefault();
+            isDragging = true;
+            [origX, origY] = getBgPos();
+            startX = e.clientX;
+            startY = e.clientY;
+            elem.style.cursor = "grabbing";
+            // on fixe no-repeat pour éviter la répétition
+            elem.style.backgroundRepeat = "no-repeat";
+          });
+
+          document.addEventListener("mousemove", (e) => {
+            if (!isDragging) return;
+            const dx = e.clientX - startX;
+            const dy = e.clientY - startY;
+            let nx = origX + dx;
+            let ny = origY + dy;
+
+            // 4) Clamp : une fois l'image chargée
+            const Cw = elem.clientWidth;
+            const Ch = elem.clientHeight;
+            if (Iw && Ih) {
+              console.log(
+                `Cadre largeur : ${Cw}, Cadre hauteur : ${Ch}\nImage largeur ${Iw}, Image hauteur ${Ih}`
+              );
+              // bornes horizontales
+
+              /*
+               * Ih et Iw : Height et width de l'image d'origine (source)
+               * Ch et Cw : Height et width du cadre (canvas)
+               * minX : Taille minimale de la position du background-position sur l'axe horizontal en px.
+               * maxX : Taille maximale de la position du background-position sur l'axe horizontal en px.
+               * minY : Taille minimale de la position du background-position sur l'axe vertical en px.
+               * maxY : Taille minimale de la position du background-position sur l'axe vertical en px.
+               * nx et ny : Position du background-position manipulé par l'utilisateur.
+               */
+              const minX = Math.min(Cw - Iw * zoom, 0);
+              const maxX = 0;
+              // bornes verticales
+              const minY = Math.min(Ch - Ih * zoom, 0);
+              const maxY = 0;
+              // clamp X et Y
+              nx = Math.max(minX, Math.min(maxX, nx));
+              ny = Math.max(minY, Math.min(maxY, ny));
+            }
+
+            elem.style.backgroundPosition = `${0}px ${ny}px`;
+          });
+
+          document.addEventListener("mouseup", () => {
+            if (!isDragging) return;
+            isDragging = false;
+            elem.style.cursor = "";
+          });
+
+          // éviter la sélection de texte/image native
+          elem.addEventListener("dragstart", (e) => e.preventDefault());
+
+        },
+        { once: true }
+      );
+    });
+  }
+
   // to set data-data for every element when opening the page
   $(".siteeditor").each(function () {
     dataData(this);
@@ -888,6 +1003,7 @@ let NEWSITEEDITOR = (function () {
 
   //nseFileEditor
   //nseImageEditor(false);
+  nseBgImageEditor();
 
   // define the public API
   var API = {};