css 如何在JavaScript中设置图片的开始和结束点

tcomlyy6  于 2023-05-02  发布在  Java
关注(0)|答案(1)|浏览(161)

我有一张画布,里面画了一些圆圈。这些圆圈非常重要,因为它们可以让我画线。我有一些图像,用户可以拖放在画布内,但我想设置一个起点和终点的图像,所以当我把它放在画布内的起点停留在第一个圆圈和终点2圈后。我希望电路(图像)捕捉到试验板(圆网格)中的孔。类似这样的东西,但带有丢弃的图像:

**

//Javascript per la creazione di cirucuiti elettrici

const NUMERO_CICLO = 990;
const NUMERO_CICLO_INTERNO = 60;

const resistor = document.getElementById('component_circuit_resistor');
const condensator = document.getElementById('component_circuit_condensator');
const tranistor = document.getElementById('component_circuit_tranistor');
const alimentator = document.getElementById('component_circuit_alimentator');
const circuit = document.getElementById('components_circuit');
const back_button = document.getElementById('back-button');
const clear_button = document.getElementById('clear-button');
const draggable = document.querySelectorAll('.draggable');
const container = document.querySelectorAll('.container');
const canvas = document.getElementById('canvas');
const foward_button = document.getElementById('foward-button');

/** EDIT START */
const draggableImages = document.querySelectorAll('img[draggable]');

for (let i = 0; i < draggableImages.length; i++)
  draggableImages[i].ondragstart = (ev) => {
    ev.dataTransfer.setData('text/plain', i.toString());
  };

canvas.ondragover = (ev) => ev.preventDefault(); // IMPORTANT

const orderStack = [];
const deletedOrderStack = [];

const drawnImageData = [];
const deletedImageData = [];

canvas.ondrop = (ev) => {
  const index = parseInt(ev.dataTransfer.getData('text/plain'));
  const img = draggableImages[index];
  drawnImageData.push({
    img,
    x: ev.offsetX,
    y: ev.offsetY
  });
  orderStack.push(1);
};
clear_button.disabled = true;
clear_button.style.cursor = 'not-allowed';
foward_button.disabled = true;
foward_button.style.cursor = 'not-allowed';
back_button.disabled = true;
back_button.style.cursor = 'not-allowed';
/** EDIT END */

canvas.width = 1500;
canvas.height = 855;
canvas.style.backgroundColor = 'lightgrey';
circuit.appendChild(canvas);
canvas.style.borderRadius = '10px';
canvas.style.marginLeft = 'auto';
canvas.style.marginRight = 'auto';
canvas.style.display = 'block';
const ctx = canvas.getContext('2d');

const circles = [];
const lines = [];
const lines_c = [];
var deletedLines = [];

for (let y = 20; y <= NUMERO_CICLO; y += 20) {
  for (let i = 0; i < NUMERO_CICLO_INTERNO; i++) {
    circles.push({
      x: 13 + i * 25,
      y,
      radius: 5,
      color: 'grey',
    });
  }
}

let startCircle = null;
let endCircle = null;
var priorita = null;

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  circles.forEach((circle) => {
    ctx.beginPath();
    ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
    ctx.fillStyle = circle.color;
    ctx.fill();
  });
  lines.forEach((line) => {
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.moveTo(line.start.x, line.start.y);
    ctx.lineTo(line.end.x, line.end.y);
    ctx.stroke();
  });
  if (startCircle && endCircle) {
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.moveTo(startCircle.x, startCircle.y);
    ctx.lineTo(endCircle.x, endCircle.y);
    ctx.stroke();
  }
  /** EDIT START */
  for (const data of drawnImageData)
    ctx.drawImage(data.img, data.x, data.y, data.img.width, data.img.height);

  /** EDIT END */
  requestAnimationFrame(draw);
  if (drawnImageData.length > 0 || lines.length > 0) {
    clear_button.disabled = false;
    clear_button.style.cursor = 'pointer';
    back_button.disabled = false;
    back_button.style.cursor = 'pointer';
  }
}
draw();

function goBack() {
  if (orderStack.length === 0) {
    return
  }

  if (orderStack[orderStack.length - 1] === 1 && drawnImageData.length > 0) {
    deletedImageData.push(drawnImageData.pop());
  } else if (orderStack[orderStack.length - 1] === 0 && lines.length > 0) {
    deletedLines.push(lines.pop());
  }

  deletedOrderStack.push(orderStack.pop())

  // Check if there are any items left to undo
  if (drawnImageData.length === 0 && lines.length === 0) {
    back_button.disabled = true;
    back_button.style.cursor = 'not-allowed';
    clear_button.disabled = true;
    clear_button.style.cursor = 'not-allowed';
  }
  // Enable the forward button
  foward_button.disabled = false;
  foward_button.style.cursor = 'pointer';
}

function goFoward() {
  if (deletedOrderStack.length === 0) {
    return
  }

  if (deletedOrderStack[deletedOrderStack.length - 1] === 1 && deletedImageData.length > 0) {
    drawnImageData.push(deletedImageData.pop());
    orderStack.push(deletedOrderStack.pop());
  } else if (deletedOrderStack[deletedOrderStack.length - 1] === 0 && deletedLines.length > 0) {
    lines.push(deletedLines.pop());
    orderStack.push(deletedOrderStack.pop());
  }
  // Check if there are any items left to redo
  if (deletedImageData.length === 0 && deletedLines.length === 0) {
    foward_button.disabled = true;
    foward_button.style.cursor = 'not-allowed';
  }

  // Enable the back button
  back_button.disabled = false;
  back_button.style.cursor = 'pointer';
}

function clearCanvas() {
  if (confirm('Are you sure you want to delete the circuit?')) {
    lines.length = 0;
    deletedLines.length = 0;
    lastDeleted = null;

    // clear drawn images data
    drawnImageData.length = 0;

    orderStack.length = 0
    deletedOrderStack.length = 0

    clear_button.disabled = true;
    clear_button.style.cursor = 'not-allowed';
    foward_button.disabled = true;
    foward_button.style.cursor = 'not-allowed';
    back_button.disabled = true;
    back_button.style.cursor = 'not-allowed';
  }
}

function getNearestCircle(x, y) {
  let nearestCircle = null;
  let nearestDistance = Infinity;
  circles.forEach((circle) => {
    const distance = Math.sqrt((circle.x - x) ** 2 + (circle.y - y) ** 2);
    if (distance < nearestDistance && distance < 30) {
      nearestCircle = circle;
      nearestDistance = distance;
    }
  });
  return nearestCircle;
}

let isDrawing = false;

canvas.addEventListener('mousedown', (event) => {
  const x = event.offsetX;
  const y = event.offsetY;
  const circle = getNearestCircle(x, y);
  if (circle) {
    startCircle = circle;
    endCircle = {
      x,
      y
    };
    isDrawing = true;
  }
});

canvas.addEventListener('mousemove', (event) => {
  if (isDrawing) {
    endCircle.x = event.offsetX;
    endCircle.y = event.offsetY;
  } else {
    const x = event.offsetX;
    const y = event.offsetY;
    const circle = getNearestCircle(x, y);
    if (circle) {
      circles.forEach((circle) => {
        circle.color = 'grey';
      });
      circle.color = 'red';
    } else {
      circles.forEach((circle) => {
        circle.color = 'grey';
      });
    }
  }
});

canvas.addEventListener('mouseup', () => {
  if (isDrawing) {
    const x = endCircle.x;
    const y = endCircle.y;
    const circle = getNearestCircle(x, y);
    if (circle) {
      lines.push({
        start: startCircle,
        end: circle,
      });

      orderStack.push(0);
    }
    isDrawing = false;
    startCircle = null;
    endCircle = null;
  }
});

//back_button.addEventListener("click", goBack);
//foward_button.addEventListener("click", goBack);
clear_button.addEventListener('click', clearCanvas);

var back_clicked = false;
back_button.addEventListener('click', function() {
  back_clicked = true;
  goBack();
  back_clicked = false;
});

var foward_clicked = false;
foward_button.addEventListener('click', function() {
  foward_clicked = true;
  goFoward();
  foward_clicked = false;
});
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
html,body{
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    background-color: #ede7e1;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 14px;
    color: #333;
    line-height: 1.5;
    overflow-x: hidden;
}

img{
    width: 100%;
    height: 100%;
}

#h1_disegna{
    text-align: center;
}
#h1_breadboard{
    text-align: center;
    position: relative;
    top: -550px;
}

#h1_titolo{
    font-size: 60px;
    text-align: center;
}
#h3_componenti_circuit{
    border-style: solid;
    width: 100px;
    border-color: black rigid 1px;
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
    background-color: sandybrown;
    position: relative;
    top: 85px;
}

#h3_componenti_br{
    border-style: solid;
    width: 100px;
    border-color: black rigid 1px;
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
    background-color: sandybrown;
    position: relative;
    top: -500px;
}

#h4_footer{
    font-size: 26px;
}

.elementi_disegno{
    position: relative;
    top: -520px;
}

#canvas{
    position: relative;
    top: -520px;
    
}

#back-button{
    position: relative;
    top: 62%;
    left: 42.5%;
    transform: translate(-50%, -50%);
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 24px;
    background-color: rgba(244, 165, 96, 0.473);
    border-radius: 6px;
}

#foward-button{
    position: relative;
    top: 62%;
    left: 43%;
    transform: translate(-50%, -50%);
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 24px;
    background-color: rgba(244, 165, 96, 0.473);
    border-radius: 6px;
}

#clear-button{
    border-radius: 6px;
    position: relative;
    top: 62%;
    left: 44.5%;
    transform: translate(-50%, -50%);
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 24px;
    background-color: rgba(244, 165, 96, 0.473);
}
#components_circuit_border{
    border-style: solid;
    width: 100px;
    border-color: black rigid 1px;
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
    background-color: antiquewhite;
    cursor: move;
    position: relative;
    top: 85px;
}

#components_br_border{
    border-style: solid;
    width: 100px;
    border-color: black rigid 1px;
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
    background-color: antiquewhite;
    cursor: move;
    position: relative;
    top: -500px;
}

#components_circuit{
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
}
.footer{
    text-align: center;
    background-color: darkgray;
    left: 0;
    margin-bottom: 0;
    height: 40px;
    width: 100%;
}

.material-symbols-outlined{
    display: inline-flex;
    vertical-align: -3px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
    <link rel="stylesheet" href="style.css">
    <title>From Circuit to Breadboard</title>
</head>
<body>
    <h1 class="ml2" id="h1_titolo">From Circuit to Breadboard</h1>
    <div class="container">
        <div class="components">
            <div id="components_circuit">
                <h3 id ="h3_componenti_circuit">Componenti:</h3>
                    <ul id="components_circuit_border">
                        <li><img id ="component_circuit_resistor" src="https://upload.wikimedia.org/wikipedia/commons/e/ee/Resistor_symbol_America.svg" height="50" draggable="true"></li>
                        <br><br>
                        <li><img id = "component_circuit_condensator" src="images/circuit_condensator.png" height="50" draggable="true"></li>
                        <br><br>
                        <li><img id="component_circuit_transistor" src="images/circuit_transistor.png" height="50" draggable="true"></li>
                        <br><br>
                        <li><img id="component_circuit_alimentator" src="images/circuit_alimentator.png" height="50" draggable="true"></li>
                    </ul>
                <div class = "elementi_disegno">
                    <h1 id ="h1_disegna">Disegna il tuo circuito!</h1>
                <button id="back-button">Indietro
                    <span class="material-symbols-outlined">undo</span>
                </button>
                <button id="foward-button">Avanti
                    <span class="material-symbols-outlined">redo</span>
                </button>
                <button id="clear-button">Clear All
                    <span class="material-symbols-outlined">delete</span>
                </button>
                <canvas id = "canvas" class = "dropzone"></canvas>
                </div>
            </div>
            <br>
            <br>
            <div id="components_br">
                <h1 id = "h1_breadboard">Breadboard</h1>
                <h3 id ="h3_componenti_br">Componenti:</h3>
                <ul id="components_br_border">
                    <li><img id = "component_br_resistor" src="images/br_resistor.png" height="50" draggable="true"></li>
                    <br><br>
                    <li><img id = "component_br_condensator" src="images/br_condensator.png" height="50" draggable="true"></li>
                    <br><br>
                    <li><img id = "component_br_transistor" src="images/br_transistor.png" height="50" draggable="true"></li>
                    <br><br>
                    <li><img id="component_br_alimentator" src="images/br_alimentator.png" height="50" draggable="true"></li>
                </ul>   
            </div>
        </div>
    </div>
    <footer class="footer">
        <div>
           <h4 id ="h4_footer">Sito web progettato e realizzato da Skerdi Velo, Davide Rossini, Andrea Quagliotti <span class="material-symbols-outlined">copyright</span>2023</h4>
        </div>
    </footer>
    
    <script src="script.js"></script>
</body>
</html>

**

为了更好地理解,尝试拖放一个图像,您可以看到图像并不关心圆圈。

unhi4e5o

unhi4e5o1#

做了一些研究,这段代码使它为我工作。希望这对你有帮助

canvas.ondrop = (ev) => {
  const index = parseInt(ev.dataTransfer.getData('text/plain'));
  const img = draggableImages[index];
  const circleIndex = Math.floor(ev.offsetY / 20) * NUMERO_CICLO_INTERNO + Math.floor((ev.offsetX - 13) / 25);
  const startCircle = circles[circleIndex];
  const endCircle = circles[circleIndex + 2];
  drawnImageData.push({
    img,
    x: startCircle.x - img.width / 2,
    y: startCircle.y - img.height / 2
  });
  orderStack.push(1);
};

相关问题