The following seems to work now:
let canvas = document.querySelector("#can");
let arr1,arr2,ctx = canvas.getContext("2d");
const getCoords=()=>[inp1.value.split("-").map(v=>+v),inp2.value.split("-").map(v=>+v)],
drwline=(a,b,c,d)=>
{ctx.beginPath();ctx.moveTo(a,b);ctx.lineTo(c,d);ctx.stroke();ctx.closePath();}
document.getElementById("createcanvas").addEventListener("click" , ()=>{
let [arr1,arr2]=getCoords();
ctx.rect(...arr1);
ctx.rect(...arr2);
ctx.stroke();
});
document.getElementById("connect").addEventListener("click" , ()=>{
let [[a,b,c,d],[e,f,g,h]]=getCoords();
drwline(a,b,e,f);
drwline(a+c,b,e+g,f);
drwline(a,b+d,e,f+h);
drwline(a+c,b+d,e+g,f+h);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="inp1" value="10-10-200-200">
<input type="text" name="" id="inp2" value="20-20-230-230">
<button id="createcanvas">Create</button>
<button id="connect">Connect</button>
<canvas id="can" width="500px" height="500px" style="background-color: #ccc;display:block;"></canvas>
</body>
<script src="script.js"></script>
</html>
Explanation:
I moved the input-reading section into your event handling functions for your #createcanvas
and #connect
buttons. For this I created the helper function getCoords()
. This collects the input values and returns them into two arrays that are then local to the individual functions.
You should always use document.getElementbyId()
or some suitable document.querySelector()
function to get the DOM element reference, since otherwise the objects might get in conflict with variables declared in the global name space.
In a later edit I also shortened some of your drawing instructions, following the “DRY” (dont’t repeat yourself) paradigm: the function drwline()
now draws a line between two points.