Холст отображается только на первом изображении слайдера или подключается к нижней части каждого изображения. - PullRequest
0 голосов
/ 18 октября 2019

Поэтому я попытался сделать так, чтобы при нажатии на изображение оно рисовало круг на холсте. Предполагается, что изображение и холст накладываются друг на друга. Однако у меня есть проблема, когда у меня cnvs.style.position = 'absolute'; active все мои холсты »наложены друг на друга на первом изображении. Поэтому, если бы я щелкнул по другим изображениям, круг был бы нарисован на первом изображении, а не на том, на котором щелкнули. Однако, если я закомментирую cnvs.style.position = 'absolute';, холст будет связан с нижней частью изображения, а не наложен. Мне нужно сделать так, чтобы каждый холст и изображение накладывались друг на друга, чтобы при нажатии на одно изображение появлялся круг. Я думаю, что у меня проблема css, но я не знаю, как ее исправить.

document.body.onload = addElement;

      function addElement() {
            
            // image path
            const imagePath = ['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'];
            
            for (const image of imagePath) {
                  // get the item id of an image
                  var slice = image.slice(26, 34);
                  var id = image;
                  var hdnName = document.getElementById("sendServ"); 

                  const img = document.createElement("img");
                  img.src = image;
                  img.classList.add("new");
                  img.id = slice;

                  const cnvs = document.createElement("canvas");
                  cnvs.classList.add("suiteiCanvas");
                 
                 // cnvs.style.position = 'absolute';
                  cnvs.style.left = img.offsetLeft + "px";
                  cnvs.style.top = img.offsetTop + "px";
                  cnvs.style.display = 'none';

                  var ctx = cnvs.getContext("2d");
                  ctx.clearRect(0, 0, cnvs.width, cnvs.height);
                  ctx.beginPath();
                  ctx.arc(100, 75, 50, 0, 2 * Math.PI, false);
                  ctx.lineWidth = 15;
                  ctx.strokeStyle = '#FF0000';
                  ctx.stroke();

                  var div = document.createElement("div");
                  var div1 = document.createElement("div");
                  div.id = id;
                  div1.id = '1';
                  div.classList.add("image");


                  img.onclick = function draw() {
                        cnvs.style.display = '';
                        hdnName.value = img.id;
                  };

                  cnvs.onclick = function remove() {
                        cnvs.style.display = 'none';
                        hdnName.value = null;
                  };

                  document.getElementById('suitei-slider').appendChild(div);
               
                  document.getElementById(image).appendChild(img);
                  document.getElementById(image).appendChild(cnvs);
               
               
            }
      }
      
// slick slider      
   
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);
  
}
<div class="multiple-items" id="suitei-slider"></div>
<input type="hidden" id="sendServ">

Ответы [ 2 ]

1 голос
/ 18 октября 2019

Вам нужно установить свои холсты в position: absolute внутри контейнера в position: relative, чтобы ваши холсты все еще содержались в контейнере. Поскольку контейнеры не находятся в position: absolute, они не накладываются, но их содержимое будет накладываться, поэтому ваши полотна будут накладываться на изображения.

Затем вы должны отцентрировать свои холсты (я подозреваю), поэтому я установил размеры холстов (на данный момент они жестко запрограммированы) и зафиксировал положение x круга.

Iнадеюсь, это то, что вы искали.

document.body.onload = addElement;

      function addElement() {
            
            // image path
            const imagePath = ['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'];
            
            for (const image of imagePath) {
                  // get the item id of an image
                  var slice = image.slice(26, 34);
                  var id = image;
                  var hdnName = document.getElementById("sendServ"); 

                  const img = document.createElement("img");
                  img.src = image;
                  img.classList.add("new");
                  img.id = slice;

                  const cnvs = document.createElement("canvas");
                  cnvs.classList.add("suiteiCanvas");
                 
                 // cnvs.style.position = 'absolute';
                  cnvs.style.left = img.offsetLeft + "px";
                  cnvs.style.top = img.offsetTop + "px";
                  cnvs.style.display = 'none';
                  cnvs.width = 150;
                  cnvs.height = 150;

                  var ctx = cnvs.getContext("2d");
                  ctx.clearRect(0, 0, cnvs.width, cnvs.height);
                  ctx.beginPath();
                  ctx.arc(75, 75, 50, 0, 2 * Math.PI, false);
                  ctx.lineWidth = 15;
                  ctx.strokeStyle = '#FF0000';
                  ctx.stroke();

                  var div = document.createElement("div");
                  var div1 = document.createElement("div");
                  div.id = id;
                  div1.id = '1';
                  div.classList.add("image");


                  img.onclick = function draw() {
                        cnvs.style.display = '';
                        hdnName.value = img.id;
                  };

                  cnvs.onclick = function remove() {
                        cnvs.style.display = 'none';
                        hdnName.value = null;
                  };

                  document.getElementById('suitei-slider').appendChild(div);
               
                  document.getElementById(image).appendChild(img);
                  document.getElementById(image).appendChild(cnvs);
               
               
            }
      }
      
// slick slider
.image {
  position: relative; /* add this */
  user-select: none; /* and this maybe */
}

canvas.suiteiCanvas{
  height: auto; 
  width: auto;
  height: 150px;
  max-width: 150px;
  /*margin-left: 100px; 
  margin-right: 100px;*/
  border:3px solid rgb(20, 11, 11);
  position: absolute; /* add this */
}

#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);
  
}
<div class="multiple-items" id="suitei-slider"></div>
<input type="hidden" id="sendServ">
0 голосов
/ 18 октября 2019

На всякий случай, если вам интересно, что означает каждая строка, это более чистый код с комментариями во многих строках ... для моего понимания ваш код немного запутан. Вы должны использовать больше функций, чтобы быть более читабельными и т. Д.

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;
const images = {
  height: 50,
  width: 50,
  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'
  ]
}

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];
    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);
    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();

  //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);
  }
}

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();
}

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;
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);

}
<body></body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...