I am making a javascript game and I would like to be able to add a main menu but I don’t know exactley how. I am lookign up for a way to make filltext() clickable but to no avail. I have looked it up but have found no answer that suites my needs. The games protoype can be viewed here: sketchy.idreesinc.com . Does anyone know anyway to implement this? I am using javacript and HTML5’s canvas element but I would prefer javascript. Thanks!
Share
Things to know about HTML and canvas first
DOM
HTML elements are part of the DOM (the Document Object Model) which is the data structure of a webpage. DOM elements can have trigger events (like
click) and event listeners react to those events.browser
Your web browser converts the DOM elements into pixels on your screen. It also handles input and figures out what element’s events to trigger if you click on the page.
canvas
The
canvaselement allows you to render bitmap images. You basically set the colors on a grid of pixels through some javascript calls to make pretty pictures.what that all means
When you create a link element in HTML (the
<a>tag) the browser renders the text and attaches a click listener to the element so the link actually works.When you use javascript to draw the pixels on the canvas the browser’s understanding of the DOM stops at the canvas. The browser knows about the DOM and the DOM knows about the canvas but it doesn’t keep track of the individual items drawn in the canvas.
The answer
You can’t actually attach an event to the text in the canvas but there are many ways to get the desired behavior of click the text, something happens.
One way would be to attach a click event to the
canvasbut instead of a simple event listener that always runs this event listener would need to check to see if the click happened on the text or somewhere else on the canvas.Event listener functions get called with an
Eventargument which has information about the event.Things to google
Some quick reading about these should get you started towards a working menu.