0

So I'm trying to make snake. The snake function is the green block that moves with the arrows, and I'm trying to make another block that will be the fruit. But at the moment I'm trying to make a button that is in the canvas, that when clicked will run all the functions for the game.
Here is my html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake</title>
    <link rel="stylesheet" href="snake.css">
</head>
<body>

    <input type="button" value="Play Snake" onclick="play()" value="test">
    <canvas class="canvas"></canvas>

    <script src="snake.js"></script>
    <script src="fruit.js"></script>

</body>
</html>

here is my javascript

const canvas = document.querySelector('canvas')

canvas.height = window.innerHeight
canvas.width = window.innerWidth

let x = 580
let y = 275
let dx = 0
let dy = 0
const c = canvas.getContext('2d')


function snake(){
    requestAnimationFrame(snake)
    c.clearRect(0,0, innerWidth,innerHeight)
    c.beginPath()
    c.fillStyle = 'rgb(0,128,0)'
    c.fillRect(x, y ,20 ,20)

        if (x > innerWidth - 20 || x < 0 ){
           alert('You Lose!'),x = 580, y = 275, dx = 0, dy = 0}

        if (y > innerHeight -20 || y < 0 ){
            alert('You Lose!'),x = 580, y = 275, dx = 0, dy = 0}

        x += dx
        y += dy

document.onkeydown = function(e){
    e = e || window.event;
    var key = e.which || e.keyCode
    if (key == 37){dx = -4, dy = 0}
    if (key == 38){dy = -4, dx = 0}
    if (key == 39){dx = 4, dy = 0}
    if (key == 40){dy = 4, dx = 0}
    }
}

function fruit(){
    c.beginPath()
    c.fillStyle = '#000'
    c.fillRect(100,100,10,10)
}


function play(){
snake();
fruit()
}
matthias_h
  • 11,356
  • 9
  • 22
  • 40
  • 1
    Simplest solution: put a real ` – Bergi Apr 19 '20 at 15:30
  • Other approach: paint the button, listen to all events on your canvas element, test whether they affect to area that the button covers, have the button react accordingly. – Bergi Apr 19 '20 at 15:31
  • when you say next to, do you meen inside the canvas like this: ? I tried that, and it doesnt work, and if I just add the button after the canvass, it shows up outside of the canvas. – Drummer Gaines Apr 19 '20 at 16:29
  • No, I mean after or before, and then place it anywhere you want with CSS. – Bergi Apr 19 '20 at 16:35
  • interesting. how do I place it inside the canvas in css? could you show me an example? thx – Drummer Gaines Apr 19 '20 at 21:18
  • See e.g. https://stackoverflow.com/q/2941189/1048572 or https://stackoverflow.com/q/5453370/1048572 – Bergi Apr 19 '20 at 21:36

0 Answers0