Lab Sheet 5 - Basic JavaScript Exercises & Canvas Drawing Application
Lab Sheet 5 - Basic JavaScript Exercises & Canvas Drawing Application
b) <!DOCTYPE html>
<html>
<head>
<title>Number and its squares</title>
</head>
<body>
<script type="text/javascript">
var num = prompt("Enter a number : \n", "");
var msgstr;
if(num > 0 && num !=null){
msgstr="Number and its Squares are \n";
for(i=1;i <= num; i++)
{
msgstr = msgstr + i + " ^ 2 = " + i*i + "\n";
}
alert(msgstr);
}
else
alert("Invalid Input");
</script>
</body>
</html>
P5-B Creating a Canvas Drawing Application with HTML5 and
JavaScript
Problem Statement:
The problem statement: To create a canvas drawing application that allows users to draw on the canvas
by clicking and dragging the mouse. To achieve this, use HTML5 code that includes a canvas element
with an event attribute that listens for mousedown, mousemove, and mouseup events. These events
shoud trigger JavaScript functions that draw lines on the canvas based on the user's mouse movements.
The canvas element can be styled using CSS to have a black border. Use article, section, attributes to
enhance the web page.
Solution
<!DOCTYPE html>
<html>
<head>
<title>Canvas Example</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<header>
<h1>Canvas Example</h1>
<p>Draw on the canvas by clicking and dragging the mouse</p>
</header>
<article>
<h2>Canvas</h2>
<canvas id="myCanvas" width="400" height="400" onmousedown="startDrawing(event)"
onmousemove="drawLine(event)" onmouseup="stopDrawing(event)"></canvas>
</article>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var isDrawing = false;
function startDrawing(event) {
isDrawing = true;
var x = event.clientX - canvas.offsetLeft;
var y = event.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(x, y);
}
function drawLine(event) {
if (isDrawing) {
var x = event.clientX - canvas.offsetLeft;
var y = event.clientY - canvas.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
}
}
function stopDrawing(event) {
isDrawing = false;
}
</script>
</body> </html>
Output: