JSFiddle - React, Tailwind, and code Playground
by Andrew Dunai
HTML
<div id="div1">
<h1>Spill</h1>
</div>
<div id="div3">
<div id="box">
<canvas id="canvas" width="300px" height="450px"></canvas>
</div>
</div>
<div id="div2">
<div id="tekst"></div>
</div>
CSS
body {
margin: 0px;
margin-top: 50px;
color:red;
background-color: red;
}
h1 {
text-align: center;
}
#canvas {
border: white 1px solid;
background-color: black;
margin: auto;
}
#knapp {
text-align: center;
margin-bottom: 20px;
}
#box {
width: 300px;
margin: auto;
background-color: black;
}
#tekst {
text-align: center;;
}
#div1 {
top : 0px;
height: 100px;
width: 100%;
margin: 0px;
background-color: black;
}
#div2 {
top : 0px;
height: 100px;
width: 100%;
margin: 0px;
background-color: black;
}
#div3 {
top : 0px;
width: 100%;
margin: 0px;
background-color: black;
}
JavaScript
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var tileldig = Math.floor((Math.random() * 300) + 1);
var tekst = document.getElementById("tekst")
var kuler = [{
r: 10,
x: canvas.width / 2,
y: canvas.height - 100,
f: "red",
dy: 0
}, ]
var fiender = [{
r: 20,
x: tileldig,
y: -20,
vx: 0,
vy: 1,
}, ]
var snd = new Audio("Skudd.m4a");
var poeng = 1;
var hayre = 0;
var venstre = 0;
var opp = 0;
var ned = 0;
document.onkeydown = function tast(e) {
if (e.keyCode == 39) { // høyre
hayre = 1;
}
if (e.keyCode == 37) { // venstre
venstre = 1;
}
if (e.keyCode == 38) { // opp
opp = 1;
}
if (e.keyCode == 40) { // ned
ned = 1;
}
if (e.keyCode == 32) {
newskudd();
snd.play();
console.log("hit space")
}
if (e.keyCode == 13) {
spill();
}
}
document.onkeyup = function tast2(e) {
if (e.keyCode == 39) { // høyre
hayre = 0;
}
if (e.keyCode == 37) { // venstre
venstre = 0;
}
if (e.keyCode == 38) { // opp
opp = 0;
}
if (e.keyCode == 40) { // ned
ned = 0;
}
}
function spill() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += kuler[i].dy;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2 * Math.PI, 0);
ctx.closePath();
ctx.fill();
// WRONG PLACE!
// This part of code is called many times for each bullet!
// This is why you have player moving speed increase.
// if (venstre == 1){
// kuler[0].x -= 4;
// }
// if (høyre == 1){
// kuler[0].x += 4;;
// }
// if (opp == 1){
// kuler[0].y -= 4;
// }
// if (ned == 1){
// kuler[0].y += 4;
// }
if (kuler[0].x >= canvas.width - kuler[0].r) {
...