## Simple Javascript Programs

• 28th Jul, 2020
• 18:32 PM

## Javascript Assignment Question

1. Make a program that draws a 40 radius circle where ever the mouse is. Change the circle's fill to a new, random color whenever the mouse is clicked.
2. Make a program with four numbers in an array - 400,350,200, &75. Starting with the first number in the array, draw a gray square in the center of the page of that size (so first 400x400). Whenever the mouse is over the square, move to the next size in the array, progressing down to 75. Once at 75, stay at that size forever.

## Javascript Assignment  Solution

Program 1

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1500" height="700" onmousemove="myFunction(event,1)" onclick="myFunction(event,2)" >
</canvas>

<script>

function generateRandomColorCode()
{
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

function myFunction(e,m) {
var x = e.clientX;
var y = e.clientY;

var c = document.getElementById("myCanvas");
var rect = c.getBoundingClientRect();
var posx = e.clientX - rect.left;
var posy = e.clientY - rect.top;
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(posx, posy, 40, 0, 2 * Math.PI);
ctx.stroke();
if(m==2)
{
ctx.fillStyle = generateRandomColorCode();
ctx.fill();
}
}
</script>

</body>
</html>

Program 2

<!DOCTYPE html>
<html>

<canvas onmousemove="myFunction(event);" id="myCanvas" width="1500" height="700">

<script>
var value = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function myFunction(e)
{
ctx.clearRect(0, 0, c.width, c.height);
var cursorX = e.clientX;
var cursorY = e.clientY;
var arr = [400,350,200,75];
ctx.rect(20, 20, arr[value], arr[value]);
ctx.stroke();
ctx.fillStyle = "gray";
ctx.fill();
if(value<3)
{
value = value + 1;