Hovering on a dynamic canvas with mouse via JavaScript

Currently, I am in the process of developing a basic program as I have just started exploring JavaScript. Below is the code snippet that I have been working on:

<!DOCTYPE html>
<html>
<head>
<title>Canvas Test</title>
</head>
<body>
<section>
    <div>
        <canvas   id="canvas" width="500" height="500">

        </canvas>
    </div>
<script type="text/javascript">
var canvas;  
var ctx;

var x = 400;
var y = 300;
var dx = 2;
var dy = 4;

var a = 100;
var b = 200;
var da = 3;
var db = 5;
var WIDTH = 500;
var HEIGHT = 500; 

function circle(x,y,r) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI*2, true);
  ctx.fill();
}

function rect(x,y,w,h) {
  ctx.beginPath();
  ctx.rect(x,y,w,h);
  ctx.closePath();
  ctx.fill();
}


function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  return setInterval(draw, 10);

}

     var c = Math.floor((Math.random()*WIDTH)+1);
     var d = Math.floor((Math.random()*WIDTH)+1);
     var e = Math.floor((Math.random()*WIDTH)+1);
     var f = Math.floor((Math.random()*WIDTH)+1);
     var g = Math.floor((Math.random()*WIDTH)+1);
     var h = Math.floor((Math.random()*WIDTH)+1);


     var dc = Math.floor((Math.random()*6)+1);
     var dd = Math.floor((Math.random()*8)+1);
     var de = Math.floor((Math.random()*7)+1);
     var df = Math.floor((Math.random()*5)+1);
     var dg = Math.floor((Math.random()*6)+1);
     var dh = Math.floor((Math.random()*4)+1);

var enTimer = null;
function draw() {
  clearInterval(enTimer);


  ctx.fillStyle = "#FAF7F8";
  rect(0,0,WIDTH,HEIGHT);
  ctx.fillStyle = "#F00";
  circle(x, y, 10);

  ctx.fillStyle = "#0772A1";
  circle(a, d, 20);

  ctx.fillStyle = "#00BB3F";
  circle(a, b, 30);

  ctx.fillStyle = "#FB0";
  circle(c, d, 15);

  ctx.fillStyle = "#E7003E";
  circle(c, y, 25);

  ctx.fillStyle = "#FF7400";
  circle(e, f, 10);

  ctx.fillStyle = "#98ED00";
  circle(g, h, 25);

  ctx.fillStyle = "#3016B0";
  circle(e, h, 30);

  ctx.fillStyle = "#8C04A8";
  circle(g, f, 15);

    ctx.fillStyle = "#009D91";
    circle(x, f, 30);

  if (x + dx > WIDTH || x + dx < 0)
    dx = -dx;
  if (y + dy > HEIGHT || y + dy < 0)
    dy = -dy;

if (a + da > WIDTH || a + da < 0)
    da = -da;
  if (b + db > HEIGHT || b + db < 0)
    db = -db;

    ...

init();
function pause() {
  clearInterval(enTimer);


  ctx.fillStyle = "#FAF7F8";
  rect(0,0,WIDTH,HEIGHT);
  ctx.fillStyle = "#F00";
  circle(x, y, 10);

  ...

      var interval = getRand(200000, 000);
     enTimer = setInterval(addEnemy, interval);
}

</script>

</section>
</body>
</html>

I intend to have the animation pause when hovering over the canvas and resume once the cursor is moved out. I attempted to achieve this by using `onmouseover` and `onmouseout` but it didn't work as expected.

Please note that I prefer using JavaScript only for this functionality without incorporating any libraries like jQuery.

Answer №1

You're so close to figuring it out...

Make sure the timer you define in init() is set to public:

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  enTimer=setInterval(draw, 10);

}

Add event listeners to stop the timer on mouseover and start a new timer on mouseout:

// listen for mouseover on the canvas 

canvas.addEventListener("mouseover",doMouseOver,false);

// listen for mouseout from the canvas

canvas.addEventListener("mouseout",doMouseOut,false);


// if mouseover detected, clear the timer

function doMouseOver(){
    clearInterval(enTimer);
}


// if mouseout detected, initialize a new timer

function doMouseOut(){
    var interval = getRand(200000, 000);   // You can also make interval public for reusability
    enTimer = setInterval(addEnemy, interval);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the length property of arrays for mathematical computations

I'm currently exploring the possibility of achieving this using javascript. In my scenario, I have an array named cart that consists of objects with product.quantity, and I aim to incorporate the value of cart.length in a calculation. However, I cons ...

Methods for organizing my code to yield a callback function

I've been trying to figure this out for a while now. I had a similar question posted here: How exactly does done() work and how can I loop executions inside done()?, but it seems like my issue has evolved since then. Currently, I am loading multiple ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

Positioning a logo in HTML/CSS so that it remains fixed at the top left corner regardless of the screen size

So, I'm facing a bit of a challenge here! I'm working on coding a website with HTML/CSS and I want the logo to remain fixed at the top left corner. The issue arises when resizing the browser window on a Windows machine – my logo ends up getting ...

Create an express server that can stream mp3 files with the functionality to easily skip forward or rewind

My express server is set up to either download or stream an mp3 file, and here is the code: const express = require('express'); const fs = require('fs'); const app = express(); app.use('/mp3', express.static(__dirname + &apo ...

Using Bootstrap CSS and JavaScript specifically for carousel functionality

Custom Styles and Scripts for Bootstrap Carousel Using Carousel with Controls https://getbootstrap.com/docs/4.0/components/carousel/ <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner ...

Internet Explorer does not display CSS effectively

Having issues with CSS on Internet Explorer While this page displays correctly in Firefox, Chrome, and Opera, on IE the "date bar" is overlapping on the first <li> bar View the issue here: The current CSS code is: #content h2.other-posts { he ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Turn off automatic compilation for LESS styling

In my Eclipse environment, I am looking to have LESS compile only when explicitly triggered by mvn package. Currently, any changes made in my less file immediately update the CSS. How can I prevent this automatic behavior? <plugin> <groupId> ...

Using AngularJS to dynamically bind HTML content based on a variable’s value

I am trying to dynamically display an image of a man or a woman on a scene, depending on the gender of the person logged into my website. The ng-bind-html directive is working fine when I define "imageToLoad" statically. However, it fails when I try to gen ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

Tips for maintaining tab state using Angular Material

In my Angular 8 application with Angular Material, I have implemented four tabs where each tab allows editing. However, when going back from the edit mode to the tabs, I want the last selected tab to remain selected. My approach so far is as follows: exp ...

Dynamic content cannot have classes added to them using jQuery

When adding content dynamically, it is necessary to use an event handler for a parent element using on(). However, I am facing an issue where the class added with addClass on dynamically generated content disappears immediately. Let's take a look at ...

In my current project, I am developing a memory game using Ionic and Angular. The game involves displaying an ever-expanding list of numbers for the user to memorize, followed by the user typing

I am trying to make each number in an array appear and then disappear one by one. However, I have encountered an issue where only the last number shows up when there are multiple numbers in the array. I believe the problem lies within the for loop, but I h ...

Set the camera to view the world from a y-coordinate of 0 and descend

How can I make the top of the render area in Three.js point to y=0 in the world? I also want the camera to look straight (lookAt) These are my current values: camera = PerspectiveCamera camera.position.z = 1895.8448868133867 camera.fov = 20 screen.width ...

Interested in extracting and saving data from an HTML table by retrieving values enclosed within the <tr> tags

I am interested in extracting data from a specific table and storing the values based on data attributes in a dictionary. My main challenge is figuring out how to target only the second table within the HTML file. Additionally, I'm struggling with fet ...

Acquiring the root URL with the $location service in AngularJS

I am facing a situation where I have a specific URL structure like the one shown below. http://localhost:8080/test#/users/list Upon further investigation, I discovered the following information: $location.url() returns -> "users/list" $location.path( ...

Accelerate real-time searching using javascript, php, and mysql

An innovative "live search bar" has been created using a combination of PHP and JavaScript. This feature allows users to enter a word into the search bar, prompting a database search in MySQL. index.php: <input type="text" onkeyup="getMovie(this.value ...

Steps to display the "col-md-6" div upon hovering over list items in a different div

I have been trying to make a hover action work in my HTML document. I've managed to get it to work only when the description is a child of the li tag, but I want the description to be displayed as a separate div. <div class="row"> ...

Upon page load, the opencart div tab content fails to display

I'm currently using an opencart template, and I'm attempting to display some data from a MySQL table in a div tab. Initially, everything works fine. However, when I reload the browser, it doesn't display the default current div with the MySQ ...