1

I am finding it hard to get my buttons working inside a html canvas. I think that the onclick event is not being called or the canvas is over layed and drawing over them but I can't figure out why. I have tried putting the buttons on a higher z-index as demonstrated here

Can I put an HTML button inside the canvas?

but I have had no avail. Here is the code for the canvas and button

<canvas id="whiteboard" style="z-index:1; position: absolute; left: 0px; top: 0px;"></canvas>
<input type="button" style="z-index: 2" value="blue" id="blue" onclick="colorChange('#0000FF');" />

here is the script tag

<script src="assets/js/color.js"></script>

and the function I am trying to call in color.js

function colorChange(color) { alert("adadadsdasd"); var c = document.getElementById('whiteboard'); var ctx = c.getContext("2d"); ctx.fillStyle = color; }

I am fairly new to JS so I apologise if there is any rookie errors.

Community
  • 1
  • 1
Pudding
  • 533
  • 1
  • 6
  • 23
  • you can't change the z-index of an element unless you set the position to at least relative first. Try adding a position:relative; to the input tag along with the z-index:2; – mattdevio Jan 23 '16 at 04:15

2 Answers2

2

Behaviour can differ on different browsers, the below works on Firefox and Chrome (note the zindex). Fiddle at https://jsfiddle.net/p9gz8rpm/:

<canvas id="whiteboard" style="z-index:-1; position: absolute; left: 0px; top: 0px;"></canvas>

Prabindh
  • 3,356
  • 2
  • 23
  • 25
  • Thanks. However setting it to this means I cant draw on the canvas and buttons now seem to overlay. Can you use z-index with a div so that only that segment is above the canvas? – Pudding Jan 23 '16 at 04:34
  • Yes, please use the position: tag to do that appropriately (as mentioned in other answer here) – Prabindh Jan 23 '16 at 05:32
0

You forgot to add:

position: absolute;

to your button. A z-index only works if it has that set.

<input type="button" style="z-index: 2; position: absolute;" value="blue" id="blue" onclick="colorChange('#0000FF');" />

Edit:

(If you don't want to use position: absolute; Use position: relative)