Using event.client (x and y) to use for mouse coordinates to spawn a shape in HTML/JS

1.5k Views Asked by At

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.

1

There are 1 best solutions below

0
360gamegod On

Try the demo I made below :

<!DOCTYPE html>
<html>
<body>

  <canvas id="canvas" width="500" height="500" onmousedown="draw(event)" style="border:1px solid black;">Your browser does not support HTML 5.</canvas>

  <script>

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var width = 100;
    var height = 100;

    function draw(event){
      var mousex = event.clientX;
      var mousey = event.clientY;
      ctx.fillRect(mousex - (width / 2), mousey - (height / 2), width, height);
    }

  </script>
</body>
</html>

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.