Проблема с массивом: вставка массива php в массив javascript, images.url не определен - PullRequest
0 голосов
/ 23 октября 2019

Итак, у меня есть фиктивный массив, называемый images. Я помещаю массив php в массив javascript, чтобы сделать мой реальный массив похожим на форму моего фиктивного массива. Однако, когда я делаю это, я получаю images.url не определен как ошибка. Хотя они выглядят почти почти. Единственное, что отличается от моего примера массива и моего фактического массива, это то, что реальный массив - это часть пути к изображению shelf/thumbnail/O191/6337/O1916337-00.png, а мой фиктивный массив - это ссылка на изображение. Должен ли мой путь быть моим полным путем к моему изображению, чтобы мой код работал ??? Полный путь к моему изображению должен быть /check/assets/img/shelf/thumbnail/O191/6337/O1916337-00.png.

Вот как выглядит консоль для моего реального массива после его установки вimages enter image description here

Так выглядит консоль для моего фиктивного массива. enter image description here

Форма массива должна быть подходящей для моего реального массива, но я все еще получаю images.url не определен, и я не совсем уверен, почему. Любая помощь будет хорошей. Спасибо.

 document.body.onload = createHTML;

  /// my real array where I put $face into images.
  //    const images = [];
  //      images.push(<?= json_encode($face) ?>);
  //     console.log(images); 
   

      let index = 0;
      const display = "table"; // or "grid" if horizontal, but this migh depend where you place the rest of the code, cause i added the style to the body
      const x = 0;
      const y = 0;

         // dummy array
       const images = {
             height: 100,
             width: 100,
             url: [
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1",
                   "",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1",
                   "",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1",
                   "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1",
                   ""
             ]
       }; 

       console.log(images);




      function createHTML() {
            console.log("E: Execute & R: Request & I: Informative");
            //loop to go true all images
            document.body.style.display = display;
            for (const image of images.url) {
                  //each image will correspond to a canvas element
                  const canvas = document.createElement("canvas");
                  const ctx = canvas.getContext("2d");

                  //each canvas element will has is own properties (in this case all the same)
                  canvas.id = "option" + [index];
                  var canId = canvas.id;
                  canvas.height = images.height;
                  canvas.width = images.width;
                  canvas.style.padding = "10px";
                  //function to get the corresponded image of that particular canvas element
                  drawImages(canvas);
                  //add an event listener for when a user click on the particular canvas
                  canvas.addEventListener("click", optionClick, false);
                  //all html part was handle we can append it to the body
                  // document.body.appendChild(canvas);
                  var div = document.createElement("div");
                  div.id = canvas.id;
                  document.getElementById('suitei-slider').appendChild(div);
                  document.getElementById(div.id).appendChild(canvas);
                  index++;
            }
      }

      function drawImages(canvas) {
            //we need to use the getContext canvas function to draw anything inside the canvas element
            const ctx = canvas.getContext("2d");
            const background = new Image();

            // for text

            //This is needed because if the drawImage is called from a different place that the createHTML function
            //index value will not be at 0 and it will for sure with an heigher id that the one expected
            //so we are using regex to remove all letters from the canvas.id and get the number to use it later
            index = canvas.id.replace(/\D/g, "");

            //console.log('E: Drawing image ' + index + ' on canvas ' + canvas.id);

            //get the image url using the index to get the corresponded image
            background.src = images.url[index];
            //no idea why but to place the image, we need to use the onload event
            //https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
            background.onload = function() {
                  ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
            };
            background.onerror = function() {
                  const text = "インバ ど";
                  ctx.fillText(text, 0, 0 + 10 * 1);
            };
      }

      function drawX(canvas) {
            const ctx = canvas.getContext("2d");

            console.log("E: Placing X on canvas " + canvas.id);

            /*
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(images.width, images.height);
            ctx.moveTo(images.height, 0);
            ctx.lineTo(0, images.width);
            ctx.closePath();
            ctx.stroke(); */

            ctx.beginPath();
            ctx.arc(50, 50, 25, 0, 2 * Math.PI, false);
            ctx.lineWidth = 5;
            ctx.strokeStyle = "#FF0000";
            ctx.closePath();
            ctx.stroke();
            const text = "インバ ど";

      }

      function fillTextLine(canvas, x, y) {
            var text = "インバ ど";
            const ctx = canvas.getContext("2d");
            var textList = text.split(" ");
            var lineHeight = ctx.measureText("あ").width;
            textList.forEach(function(text, i) {
                  ctx.fillText(text, x, y + lineHeight * i);
            });
      }



      function clear(canvas) {
            console.log("E: clearing canvas " + canvas.id);

            canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);

            drawImages(canvas);
      }

      function optionClick(e) {
            log = true;
            const canvas = document.getElementsByTagName("canvas");
            for (const option of canvas) {
                  if (log)
                        console.log("I: User clicked at option " + e.target.id + ":" + option.id);
                  log = false;
                  if (e.target.id === option.id) {
                        console.log("R: Drawing request at canvas " + option.id);
                        drawX(option);
                  } else {
                        console.log("R: Clearing request at canvas " + option.id);
                        clear(option);
                  }
            }
      }



      //We start by calling createHTML (that will handle with all HTML elements)
      //window.onload = createHTML;
      document.body.onload = createHTML;
canvas.suiteiCanvas {
  height: auto;
  width: auto;

  max-height: 200px;
  max-width: 150px;

  margin-left: 100px;
  margin-right: 100px;
  border: 3px solid rgb(20, 11, 11);
}

#draw-btn {
  font-size: 14px;
  padding: 2px 16px 3px 16px;
  margin-bottom: 8px;
}

img.new {
  height: auto;
  width: auto;

  max-height: 200px;
  max-width: 150px;

  margin-left: 100px;
  margin-right: 100px;
  border: 3px solid rgb(20, 11, 11);

}

.multiple-items{
  max-width: 500px;
}
<body>
  <div class="multiple-items" id="suitei-slider">
  
  </div>
</body>

Пути к файлам, которые помещаются в $ result_thumbnail, обрабатываются PHP в моем контроллере.

<?php $face = [
            'height' => 100,
            'width' => 100,
            'url' => $result_thumbnail,
        ];
...