Sam kh Sam kh - 3 months ago 7
CSS Question

Display a clickable div on top of a canvas

Im dynamically creating a div that should show on top of the canvas at the position the user clicked on. The div is being creating but isnt showing. Id also like it to be clickable like a button. Any advise on what to do?

function q(event) {
event = event || window.event;

var canvas = document.getElementById('canvas'),
x = event.pageX - canvas.offsetLeft,
y = event.pageY - canvas.offsetTop;

var div = document.createElement('div');
div.style.position = "absolute";
div.style.left = x+'px';
div.style.top = y+'px';
div.style.left = "50px";
div.style.top = "50px";
div.style.backgroundColor = "black";
document.getElementsByTagName('canvas')[0].appendChild(div);

}

Answer

Here is quick demo on how you can do this: https://jsfiddle.net/od8zjeLp/2/

function q(event) {
  event = event || window.event;

  var canvas = document.getElementById('canvas-wrapper'),
    x = event.pageX - canvas.offsetLeft,
    y = event.pageY - canvas.offsetTop;

  var div = document.createElement('div');
  div.style.position = "absolute";
  div.style.background = 'red';
  div.style.width = '10px';
  div.style.height = '10px';
  div.style.left = x + 'px';
  div.style.top = y + 'px';

  canvas.appendChild(div);
}

var canvas = document.getElementById('canvas-wrapper');
canvas.addEventListener('click', q);

You can create a wrapper around the canvas element - canvas-wrapper and add the divs to the wrapper. The divs are going to be siblings to the canvas, but not children. As discussed here: Is it possible to force the html canvas tag to display children?

For production use, you may want to optimize the code: maybe avoid hard-coding widths/heights and reuse the canvas element, instead of querying the DOM on every click.