I started learning javascript after coding in java and c++ and I am trying to draw a rectangle. I can get a normal rectangle to draw If i just code normally in a script in the body but I wanna make my file look neat and have a function incase I need to call more rectangles in my program. I have googled around but I still can't figure out how to do this.
i have tried putting the function in the head section and my js file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PacMan</title>
<script scr="pac.js"></script>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//function drawRect(ctx, startX, startY, width, height, color){
//ctx.beginPath();
// ctx.rect(startX,startY,width,height);
// ctx.fillStyle = color;
// ctx.closePath();
// }
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="720"></canvas>
<script>
drawRect(ctx,10,10,10,10, "#FF0000");
// this works but i can not get the function to work
//var canvas = document.getElementById("canvas");
//var ctx = canvas.getContext("2d");
//ctx.beginPath();
// ctx.rect(900, 10, 50, 50);
// ctx.fillStyle = "#FF0000";
//ctx.fill();
// ctx.closePath();
</script>
</body>
</html>
here is the .js file i created to try to keep my functions in a nice neat order so they do not clutter my files
function drawRect(ctx,h1,h2,w1,w2, color){
//i tired at one point putting this into function
//var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}