Created
November 16, 2018 17:59
-
-
Save karbassi/a52f38a278ce26fde5827b411ed72819 to your computer and use it in GitHub Desktop.
Creating Canvas Elements using objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Position Detection</title> | |
<style> | |
#canvas { | |
border: 5px solid black; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="canvas" width="500" height="500"></canvas> | |
<script src="script.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.querySelector("#canvas"); | |
const ctx = canvas.getContext("2d"); | |
const playerPath = () => { | |
let path = new Path2D(); | |
path.rect(10, 10, 100, 100); | |
return path; | |
} | |
const obstaclePath = () => { | |
let path = new Path2D(); | |
path.rect(400, 50, 10, 100); | |
return path; | |
} | |
const player = { | |
path: playerPath(), | |
fillStyle: "green", | |
strokeStyle: "red", | |
}; | |
const obstacle = { | |
path: obstaclePath(), | |
strokeStyle: "purple", | |
}; | |
const drawPlayer = () => { | |
ctx.beginPath(); | |
if (player.fillStyle != undefined) { | |
ctx.fillStyle = player.fillStyle; | |
ctx.fill(player.path); | |
} | |
if (player.strokeStyle != undefined) { | |
ctx.strokeStyle = player.strokeStyle; | |
ctx.stroke(player.path); | |
} | |
} | |
const drawObstacle = () => { | |
ctx.beginPath(); | |
if (obstacle.fillStyle != undefined) { | |
ctx.fillStyle = obstacle.fillStyle; | |
ctx.fill(obstacle.path); | |
} | |
if (obstacle.strokeStyle != undefined) { | |
ctx.strokeStyle = obstacle.strokeStyle; | |
ctx.stroke(obstacle.path); | |
} | |
} | |
const step = () => { | |
console.log("inside step"); | |
drawPlayer(); | |
drawObstacle(); | |
} | |
step(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment