So I am trying to make a program where I click on the canvas it creates a shape in the position that I click. I am having trouble grabbing the mouse x and y coordinates and using for the x and y coordinates of my shape when I click
My HTML code:
<!doctype html>
<html lang="en">
<canvas id = "drawBoard" height = '600' width = '1330' style="border:1px solid black";></canvas>
<head>
<div id = "js">
<script src = "functions.js"></script>
</div>
<div id = "css">
<link rel = stylesheet type = "text/css" href = "main.css">
</div>
<meta charset="utf-8">
<title> Shape Drawer </title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="log"></div>
<script id = "jquery">
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "Coordinates: " + event.pageX + " , " + event.pageY );
});
</script>
<button id = "circle" onclick = "circleTrue()"> Circle </button>
<button id = "square" onclick = "squareTrue()"> Square </button>
<button id = "triangle" onclick = "triangleTrue()"> Triangle </button>
</body>
</html>
My JavaScript Code:
var shape;
var circle = false;
var square = true;
var triangle = false;
function getCoord(event){
var x = event.clientX;
var y = event.clientY;
}
document.getElementById("drawBoard");
document.getElementById('drawBoard').onclick = function() {clickSpawn()};
function clickSpawn{
fillRect(x, y, 50, 50 );
fillStyle = "black";
}
function circleTrue() {
circle = true;
square = false;
triangle = false;
}
function squareTrue() {
circle = false;
square = true;
triangle = false;
}
function triangleTrue() {
circle = false;
square = false;
triangle = true;
}
I am trying to figure out if it is possible to use my mouse x and y coordinates for a spawn location for my shape. Any help would be appreciated. Thanks.
Try the demo I made below :
The program above gets your mouse x and the mouse y when you click the canvas. Then it makes a rectangle of the specified width and height and places the center of the rectangle on your mouse pointer.