<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="200" style="border: 2px solid salmon; background-color: lightblue;"></canvas>
<p id="letter"></p>
Width of the canvas is :
<p id=cw></p>
Height of the canvas is :
<p id=ch></p>
<br>
Dots position
<br><br>
x =
<p id="x"></p>
y =
<p id="y"></p>
<script>
var x = 0;
var y = 0;
var change = true;
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
function main(){
if (change){
ctx.clearRect(0,0,canvas.width,canvas.height);
x = Math.floor(Math.random() * (canvas.width));
y = Math.floor(Math.random() * (canvas.height));
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
//ctx.fillStyle = "Purple";
//ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "Green";
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill;
document.getElementById("cw").innerHTML = canvas.width;
document.getElementById("ch").innerHTML = canvas.height;
document.getElementById("letter").innerHTML = "change = true";
change = !change;
} else {
document.getElementById("letter").innerHTML = "change = false";
//ctx.rect(0,0,canvas.width,canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.fillStyle = "yellow";
//ctx.fillRect(0, 0, canvas.width, canvas.height);
//ctx.fillStyle = "blue";
//ctx.arc(10,10,10,0,2 * Math.PI);
ctx.fill();
change = !change;
}
}
setInterval(main, 1000);//calls the function
</script>
</body>
</html>
I am trying to draw on this HTML canvas by clearing it and then drawing o circle on top so and then clearing the screen again and so it looks like the circle is flashing on for 1 second and off for 1 second.
I the commented lines in the code in case they were useful and so people can see what I’v been trying.
The x and y variables are just the coordinates of the centre of the circle.
The ‘change’ variable in a boolean. Which run the first or second part of the if loop depending on whether it is true or false.
The whole if loop is wrapped in a function called main. This called by setInterval every second on line 56, 4 from the bottom.
Any help would be greatly appreciated.
Thanks,
Shane