简体   繁体   English

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

[英]Drawing a straight line using mouse events inside a div using JavaScript

This code is work proper in canvas but I want to do this inside a div tag not in canvas. 此代码是工作画布上的正确,但我想这样做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> 

Above code is fine , But i want to draw line inside a div(direct on document page) not in canvas. 上面的代码是很好,但我想画一个div内线(直接文档页面上)不是在画布上。 I don't have any idea to do this. 我没有任何想法来做到这一点。 please help me to do this or refer me some article on this. 请帮我做这做参考我一些这方面的文章。

在此处输入图片说明 I dont have idea even how can i start. 我没有想法,甚至如何开始。 Please refer me some related answer. 请参考我的一些相关的答案。

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. 您可能有兴趣为此目的使用“ SVG”线条https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg,因为您可以轻松绘制线条。

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 为此,您将需要一个SVG容器,在这里您可以找到有关其工作方式的一些信息-> 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: 有了容器后,您需要使用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")

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM