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.