So, I am getting back into javascript coding, and I am resuming an older project. I am attempting to capture the mouse position in dedicated variables (mouseX and mouseY), for ease of use.
I have successfully managed to print out the mouse coordinates in real time, but when I try to place those coordinates into dedicated variables for ease of use, the program fails.
I believe this is most likely a simple syntax error, but I don’t know where else to look for what I’m doing wrong.
This code fragment works correctly:
document.addEventListener('mousemove', (event) => {
document.getElementById("fiddleText").innerHTML = (`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
})
However, when I try to store the mouse position in two variables, like so:
document.addEventListener('mousemove', (event) => {
mouseX = ${ event.clientX };
mouseY = ${ event.clientY };
document.getElementByID("fiddleText").innerHTML = ('Mouse X: ' + mouseX + 'Mouse Y: ' + mouseY);
})
the program fails.
I’d like to imagine that my question can be answered using only the code shown above, but last time I believed that, I was mistaken. As such, I have pasted my full javascript program below.
Note: This program is a work-in-progress, and there is a comment header stating “this is the problem area”; ignore this for now, that is an unrelated issue. Right now, I’m just trying to get the mouse to work.
//canvas elements
var canvas = document.getElementById("SnekGamCanvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener('click', function () { }, false);
/*
//some code from stack overflow: (https://stackoverflow.com/questions/9880279/how-do-i-add-a-simple-onclick-event-handler-to-a-canvas-element)
var elem = document.getElementById('canvas'),
elemLeft = elem.offsetLeft + elem.clientLeft,
elemTop = elem.offsetTop + elem.clientTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function (event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function (element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function (element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});
*/
//End of code from stack overflow
//some important variables
var px = canvas.width / 2;
var py = canvas.height / 2;
var snekColor = "#EC942D";
var clock = 0;
var mouseX = 0.5;
var mouseY = 0.5;
//classes
class clickButton {
constructor(text, color, width, height, radius) {
this.text = text;
this.color = color;
this.width = width;
this.height = height;
this.radius = radius;
}
drawButton(xpos, ypos) {
ctx.strokeStyle = "#000000"
ctx.fillStyle = this.color;
roundRect(xpos, ypos, this.width, this.height, this.radius, true, true, this.color);
ctx.fillStyle = "#000000";
ctx.strokeStyle = "#000000";
ctx.font = '40px san-serif';
ctx.strokeText(this.text, xpos + 10, ypos + 40);
ctx.fillText(this.text, xpos + 10, ypos + 40);
//draw_Ball(303, 500, 50, snekColor);
}
clickOnButton() {
}
}
//buttons
var startButton = new clickButton("Start Game", "#74B5ED", 200, 50, 20);
//images
var seel = new Image();
seel.onload = function () {
ctx.drawImage(seel, 0, 0, canvas.width, canvas.height);
}
seel.src = "https://assets.pokemon.com/assets/cms2/img/pokedex/full/086.png"
var snek_title = new Image();
snek_title.onload = function () {
ctx.drawImage(snek_title, 0, 0, canvas.width, canvas.height);
}
snek_title.src = "https://globin347.com/images/Snake%20Title.png"
//stuff about mouse moving
document.addEventListener('mousemove', (event) => {
//document.getElementById("fiddleText").innerHTML = (`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
mouseX = ${ event.clientX };
mouseY = ${ event.clientY };
document.getElementByID("fiddleText").innerHTML = ('Mouse X: ' + mouseX + 'Mouse Y: ' + mouseY);
})
//begin
var gameState = 0;
function draw() {
clock += 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//document.getElementById("fiddleText").innerHTML = ("Clock: " + clock);
if (gameState == 0) {
//this hasn't been implemented yet
startMenu();
}
else if (gameState == 1) {
//this hasn't been implemented yet either
playGame();
}
else if (gameState == 2) {
//ditto
gameOver();
}
else {
//something's wrong
ctx.drawImage(seel, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#b30000";
ctx.strokeStyle = "#000000";
ctx.font = '140px san-serif';
ctx.fillText('OH NO', 120, 120);
ctx.strokeText('OH NO', 120, 120);
ctx.fillText('IT BLOKE', 200, 630);
ctx.strokeText('IT BLOKE', 200, 630);
}
}
setInterval(draw, 10);
function startMenu() {
ctx.drawImage(snek_title, 0, 0, canvas.width, canvas.height);
/***********************************************
*
*
* This is the problem area. When the next line, startButton.drawButton(100, 100) is commented out, the rest of the code workes normally.
* However, if the line is not commented out, draw_Ball doesn't run, indicating that the program crashed somewhere in the button code.
* I would like to reiterate that the button's functionality has not yet been implemented; I am only trying to get it to display.
*
*
**********************************************/
//startButton.drawButton((canvas.width / 2) - 100, (canvas.height * (4 / 5)));
//flashing lights
/*flashTime = timer % 100;
if (timer % 2) {
draw_Ball(200, 700, 50, snekColor);
}*/
draw_Ball(200, 700, 50, snekColor);
}
function playGame() {
draw_Ball(200, 700, 50, snekColor);
draw_Ball(400, 700, 50, snekColor);
draw_Ball(300, 500, 50, snekColor);
}
function gameOver() {
}
//this function was stolen from stack overflow
function showImage(width, height, image_source, alt_text) {
var img = document.createElement("img");
img.src = image_source;
img.width = width;
img.height = height;
img.alt = alt_text;
}
function draw_Ball(bx, by, size, ballColor) {
ctx.beginPath();
ctx.arc(bx, by, size, 0, (Math.PI * 2));
ctx.fillStyle = ballColor;
ctx.fill();
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.closePath();
}
//This next function was taken from stack overflow
function roundRect(x, y, width, height, radius, stroke, fill, color) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
ctx.closePath();
return;
}
And, for good measure, my HTML and CSS files:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Portfolio</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body class="background_gradient">
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark dark-bg border-bottom box_shadow mb-0">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Portfolio</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
-->
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Resume">Resume</a>
</li>
<!----
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Art3D">3D Art</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Art2D">2D Art</a>
</li>
<!---->
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Snake">Snake</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="CodeExamples">Code Examples</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Ballad">Ballad of the Masked Bandits</a>
</li>
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="DataBaseHub">Database Hub</a>
</li>
--->
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Unavailable">???</a>
</li>
-->
<!--Temporary Links-->
</ul>
</div>
</div>
</nav>
</header>
<div class="container-fluid" id="MainDiv">
<main role="main" class="pb-0" style="width:100%">
<!--Where the other code goes-->
@{
ViewData["Title"] = "Snake Game";
}
<div class="container-fluid purple_gradient text-center">
<h1>Snake Game</h1>
</div>
<div class="buffer"></div>
<div class="container">
<div class="fancy_text_box">
<div class="container buffer">
<div class="ghostly_text_box text-center">
<h1>By the power of Javascript, here is a playable snake game.</h1>
<div class="buffer"></div>
<h1 id="fiddleText">Give it a moment to load.</h1>
</div>
<div class="buffer"></div>
<div class="ghostly_text_box text-center">
<canvas onload="draw()" class="simple_text_box" id="SnekGamCanvas" width="1000" height="1000"></canvas>
</div>
</div>
</div>
<div class="text-center">
<div class="buffer"></div>
<a class="button glo_button big_r_button big_text" asp-area="" asp-controller="Home" asp-action="Index">Back to Home</a>
<div class="buffer"></div>
</div>
<!--The code be here but if you are reading this you probably already knew that-->
<script src="~/js/Snake.js"></script>
</div>
</main>
</div>
<footer class="border-top footer dark-bg text-light">
<div class="container">
© 2021 - Portfolio - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="../jsc3d-master/jsc3d/jsc3d.js"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
/* Provide sufficient contrast against white background */
a {
color: #0366d6;
}
.btn-primary {
color: #fff;
background-image: linear-gradient(30deg, #b6e2dd, #2a5efe);
border-color: #1861ac;
}
/*Link colors*/
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px; /* Vertically center the text there */
}
/* My Stuff
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
*/
/*This gives me more control over the exact dark background color*/
.dark-bg
{
background-color: #161631;
}
.purple_gradient
{
/*The image used*/
background-image: linear-gradient(#4b1ac4, #fff);
height:100%;
width:100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.test_box_blue
{
/* A container with a solid color and an outline */
background-color: #2d1eb2;
width: 100%;
height: 100%;
margin: 0px;
}
.test_box
{
border:solid #000000;
}
#MainDiv
{
padding:0;
margin:0;
left:0;
top:0;
width:100%;
height:100%;
}
.tundra_backround
{
background-image: url('../images/Tundra_Fixed.png');
width:100%;
height:100%;
}
.white_space_box
{
height:50 px;
}
.background_gradient
{
background-image:linear-gradient(320deg, #fff, #96cbde);
}
.glo_button
{
min-width: 30%;
height: 20%;
border-radius: 25px;
padding: 20px;
margin: 10px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
transition-duration: 0.4s;
border: 4px solid #000;
}
.big_r_button {
background-color: #a10000;
color: #fff;
}
.big_r_button:hover {
color: #fff;
background-color: #4e0505;
}
.big_b_button {
background-color: #080e9f;
color: #fff;
}
.big_b_button:hover {
color: #fff;
background-color: #161631;
}
.big_g_button {
background-color: #0a7727;
color: #fff;
}
.big_g_button:hover {
color: #fff;
background-color: #07340e;
}
.big_p_button {
background-color: #6f1cbf;
color: #fff;
}
.big_p_button:hover {
color: #fff;
background-color: #2a073e;
}
.buffer
{
padding: 20px;
}
.big_text
{
font-size: 60px;
font-family:'Times New Roman', Times, serif;
text-shadow: 2px 2px rgb(12 14 39 / 0.67);
}
.fancy_text_box{
background-image: linear-gradient(300deg, #ece1c4, #c99e69);
border-radius: 25px;
border: 4px solid #5d3c08;
}
.simple_text_box{
background-color: #fff;
border: 2px solid #000;
}
.ghostly_text_box{
background-color: rgb(255 255 255 / 0.60);
border-radius: 25px;
padding: 10px;
border: 3px solid #000;
}
.thick_border{
border: 4px solid #000;
}
.black_and_white_gradient{
background-image: linear-gradient(310deg, #fff, #000);
}
.red_border{
padding: 0px;
margin: 0px;
border: 4px solid #8f0000;
}
.model_box{
border: 4px solid #000;
background-color: #fff;
border-radius: 25px;
}
.image_box{
border: 4px solid #000;
background-color: #fff;
}
.chain_image_box {
border-top: 4px solid #000;
border-left: 4px solid #000;
border-right: 4px solid #000;
border-bottom: 0px;
background-color: #fff;
}
.margin_setter {
margin: 20px;
padding: 20px;
}
#model_display_1{
}
I apologize for asking such a simple question, but I don’t know where to look to find an existing answer.