Skip to content

Commit 908d0bc

Browse files
authored
Merge pull request #840 from gurjott/simple_drawing_game
added simple drawing game
2 parents d2a2989 + 633a2b4 commit 908d0bc

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

DrawingGame/gurjott/index.html

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Simple Drawing Game</title>
7+
<link rel="stylesheet" href="styles.css">
8+
</head>
9+
<body>
10+
<h1>Simple Drawing Game</h1>
11+
<canvas id="canvas" width="400" height="400"></canvas>
12+
<button id="clear-btn">Clear</button>
13+
<script src="script.js"></script>
14+
</body>
15+
</html>

DrawingGame/gurjott/script.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Get canvas element and drawing context
2+
const canvas = document.getElementById('canvas');
3+
const ctx = canvas.getContext('2d');
4+
5+
// Variables for tracking drawing state
6+
let drawing = false;
7+
let lastX = 0;
8+
let lastY = 0;
9+
10+
// Set line style
11+
ctx.strokeStyle = 'black';
12+
ctx.lineWidth = 2;
13+
14+
// Function to start drawing
15+
function startDrawing(e) {
16+
drawing = true;
17+
[lastX, lastY] = [e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop];
18+
}
19+
20+
// Function to draw a line
21+
function draw(e) {
22+
if (!drawing) return;
23+
24+
ctx.beginPath();
25+
ctx.moveTo(lastX, lastY);
26+
[lastX, lastY] = [e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop];
27+
ctx.lineTo(lastX, lastY);
28+
ctx.stroke();
29+
}
30+
31+
// Function to stop drawing
32+
function stopDrawing() {
33+
drawing = false;
34+
ctx.closePath();
35+
}
36+
37+
// Event listeners for drawing
38+
canvas.addEventListener('mousedown', startDrawing);
39+
canvas.addEventListener('mousemove', draw);
40+
canvas.addEventListener('mouseup', stopDrawing);
41+
canvas.addEventListener('mouseout', stopDrawing);
42+
43+
// Clear canvas button
44+
const clearButton = document.getElementById('clear-btn');
45+
clearButton.addEventListener('click', () => {
46+
ctx.clearRect(0, 0, canvas.width, canvas.height);
47+
});

DrawingGame/gurjott/styles.css

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
body {
2+
font-family: Arial, sans-serif;
3+
text-align: center;
4+
}
5+
6+
canvas {
7+
border: 2px solid #000;
8+
}
9+
10+
button {
11+
margin-top: 10px;
12+
}

0 commit comments

Comments
 (0)