0

This code is work proper in canvas but I want to do this inside a div tag not in canvas.

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>

Above code is fine , But i want to draw line inside a div(direct on document page) not in canvas. I don't have any idea to do this. please help me to do this or refer me some article on this.

enter image description here I dont have idea even how can i start. Please refer me some related answer.

Shah Alam
  • 87
  • 8

1 Answers1

1

First of all, let me apologyze for my enlgish, i'll try my best to explain!

You may be interested on using "SVG" lines for this purpose https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg since you can draw lines easly.

To acomplish this, you will need and SVG container, here you can find some information about how it works -> https://www.w3schools.com/html/html5_svg.asp

Once you have the container, you need to create and move lines inside using javascript, to do so, you need the following code:


    //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")

i'll give you this example that i made, its not the best but i hope you will find it usefull!

    <!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>

ithan
  • 360
  • 4
  • 15