使用JavaScript在div内使用鼠标事件绘制直线

时间:2019-01-10 11:09:38

标签: javascript html svg

此代码在画布中正常工作,但我想在不在画布中的div标签中执行此操作。

var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;

var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];

function draw() {
  ctx.fillStyle = "#333333";
  ctx.fillRect(0, 0, canvasWidth, canvasHeight);

  ctx.strokeStyle = "black";
  ctx.lineWidth = 2;
  ctx.beginPath();

  for (var i = 0; i < existingLines.length; ++i) {
    var line = existingLines[i];
    ctx.moveTo(line.startX, line.startY);
    ctx.lineTo(line.endX, line.endY);
  }

  ctx.stroke();

  if (isDrawing) {
    ctx.strokeStyle = "darkred";
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(mouseX, mouseY);
    ctx.stroke();
  }
}

function onmousedown(e) {
  if (hasLoaded && e.button === 0) {
    if (!isDrawing) {
      startX = e.clientX - bounds.left;
      startY = e.clientY - bounds.top;

      isDrawing = true;
    }

    draw();
  }
}

function onmouseup(e) {
  if (hasLoaded && e.button === 0) {
    if (isDrawing) {
      existingLines.push({
        startX: startX,
        startY: startY,
        endX: mouseX,
        endY: mouseY
      });

      isDrawing = false;
    }

    draw();
  }
}

function onmousemove(e) {
  if (hasLoaded) {
    mouseX = e.clientX - bounds.left;
    mouseY = e.clientY - bounds.top;

    if (isDrawing) {
      draw();
    }
  }
}

window.onload = function() {
  canvas = document.getElementById("canvas");
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  canvas.onmousedown = onmousedown;
  canvas.onmouseup = onmouseup;
  canvas.onmousemove = onmousemove;

  bounds = canvas.getBoundingClientRect();
  ctx = canvas.getContext("2d");
  hasLoaded = true;

  draw();
}
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    body {
      background-color: black;
    }
    
    canvas {
      position: absolute;
      margin: auto;
      left: 0;
      right: 0;
      border: solid 1px white;
      border-radius: 10px;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <div id="drawBoard">
    <!--I want to draw here-->
  </div>
</body>

</html>

上面的代码很好,但是我想在div(不直接在画布上)内的div(直接在文档页面上)内画线。我不知道要这样做。请帮助我执行此操作,或向我推荐有关此内容的一些文章。

enter image description here 我什至不知道该如何开始。请给我一些相关的答案。

1 个答案:

答案 0 :(得分:1)

首先,让我为我的英语道歉,我会尽力解释!

您可能会对为此目的使用“ SVG”线条https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg感兴趣,因为您可以轻松绘制线条。

要完成此操作,您将需要一个SVG容器,在这里您可以找到有关其工作方式的信息-> https://www.w3schools.com/html/html5_svg.asp

有了容器后,您需要使用javascript在其中创建和移动行,为此,您需要以下代码:


    //To create 1
     document.createElementNS('http://www.w3.org/2000/svg','line'); 
    //To select 1 
     document.querySelector('#nameOfTheLine')
    //To change its position 
    line.setAttribute('x1',x1);
    line.setAttribute('y1',y1);
    line.setAttribute('x2',x2);
    line.setAttribute('y2',y2);
    //To change its stroke so you can see it: 
    line.setAttribute("stroke", "color")

我会给你我做的这个例子,它不是最好的,但我希望你会发现它有用!

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
      #canvas{
        border: 1px solid #000;
      }
      </style>
    </head>
    <body>
      <div id="border">
        <svg id="canvas" width="500" height="400">
        </svg>
      </div>

      <script>
        /*Store the "svg" item in a variable */
        const canvas = document.querySelector('#canvas');
        //Class to store the position
        class Vector2D{
          constructor(x,y){
            this.x = x;
            this.y = y;
          }
        }

        //Variables that will store the initial and final position of the line before its drawn.
        let initialPosOfLine;
        let finalPosOfLine;
        //Variable to store the stage of the canvsa, if the user its drawing or not.
        let drawingOverCanvas = false;
        //Variable to store the current index of the line
        let lineIndex = 0;

        // Code that will be executed once the user click with the mouse in the svg.
        canvas.addEventListener('mousedown', event => {
          //If we are drawing, do nothing.
          if(drawingOverCanvas) return;
          /*Calculate position relative to div -- Done by https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element */
          var rect = canvas.getBoundingClientRect();
          var x = event.clientX - rect.left; //x position within the element.
          var y = event.clientY - rect.top;  //y position within the element.
          //Change the variable drawingOverCanvas to true since now we are drawing
          drawingOverCanvas = true;
          //Store the mouse position over the div as the initialPos;
          initialPosOfLine = new Vector2D(x , y);
          //draw a line at the starting point;
          drawToPos(initialPosOfLine, initialPosOfLine, 'line'+lineIndex , false);
        });
        // Code that will be executed once the user click with the mouse in the svg.
        canvas.addEventListener('mouseup', event => {
          //If we are not drawing, do nothing.
          if(!drawingOverCanvas) return;
          //Set the varible to "false" as we are not drawing now.
          drawingOverCanvas = false;
            /*Calculate position relative to div -- Done by https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element */
          var rect = canvas.getBoundingClientRect();
          var x = event.clientX - rect.left; //x position within the element.
          var y = event.clientY - rect.top;  //y position within the element.

          //Store the final position as a vector.
          finalPosOfLine = new Vector2D(x, y);

          //Set the line to its correct position
          drawToPos(initialPosOfLine, finalPosOfLine, 'line'+lineIndex , true);
          //Increse the index of the line for the next one.
          lineIndex++;
        });

        //Draw the line when the user move the mouse
        canvas.addEventListener('mousemove', event => {
          //if we are not drawing, do nothing.
          if(!drawingOverCanvas) return;
            /*Calculate position relative to div -- Done by https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element */
          var rect = canvas.getBoundingClientRect();
          var x = event.clientX - rect.left; //x position within the element.
          var y = event.clientY - rect.top;  //y position within the element.

          //Store the mouse position as the "final" position
          finalPosOfLine = new Vector2D(x, y);
          //Draw a line from the initialPos to the current Mouse pos.
          drawToPos(initialPosOfLine, finalPosOfLine, 'line'+lineIndex , true);
        });

        //Draw a line between 2 points, if move its true, it will move the line instead of making it
        function drawToPos(initial, final, id, move){
          //Declare a new Line in SVG
          var line = document.createElementNS('http://www.w3.org/2000/svg','line');

          //If we are moving and existent line, set "line" to the current line, else, give to the new line the id attribute.
          if(move){ line = document.querySelector('#'+id) } else { line.setAttribute('id',id) };
          // If we are creating a new line, define its initial position
          if(!move) line.setAttribute('x1',initial.x);
          if(!move) line.setAttribute('y1',initial.y);
          //Define its final position
          line.setAttribute('x2',final.x);
          line.setAttribute('y2',final.y);
          //Define its stroke.
          line.setAttribute("stroke", "black")
          //Apend the line to the SVG canvas
          canvas.append(line);
        }
      </script>
    </body>
    </html>