In: Computer Science
Write an HTML/Javascript canvas program that displays a black dot in the center after the user presses the 's' button on the keyboard.
Hint: Canvas size should be 500x500 and the black dot should only appear after pressing 's'.
Answer:
Raw code:
<!-- html tag -->
<!DOCTYPE html>
<html>
<head>
<!-- head tag -->
<title>Canvas</title>
</head>
<!-- body -->
<body>
<!-- center tag to display
contnets in the center of page -->
<center>
<!-- heading
2 tag to show output on page -->
<h2>Press
's' on keyboard to display dot in the center of
canvas</h2>
<!-- canves
widh and height -->
<canvas id="myCanvas"
width="500" height="500" style="border:1px solid
#d3d3d3;">
</canvas>
<!-- java script code
-->
<script
type="text/javascript">
// action
listenter to check for s code
window.addEventListener('keydown',function(e)
{
// key variable
var key =
e.keyCode;
//if key pressed
is s
if(key ==
83){
//get the id
var canvas =
document.getElementById('myCanvas');
//get the mid point
var context =
canvas.getContext('2d');
var centerX =
canvas.width / 2;
var centerY =
canvas.height / 2;
//radius of the
dot change it according to your wish
var radius =
10;
//draw the
shape
context.arc(centerX, centerY, radius, 0, 2 *
Math.PI, false);
context.fill();
}
});
//close the
script tag
</script>
<!-- close the center tag
-->
</center>
<!-- close the body tag
-->
</body>
<!-- close the html tag -->
</html>
Editor:
output:
after key pressed
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.