0

I am building a custom WordPress block using ES5, and I have a function in the edit to get the canvas:

function imgclickHandler(event) {
  myPics = document.getElementById('myPics');
  context = myPics.getContext('2d');
  isDrawing = true;
  x = event.clientX;
  y = event.clientY;
  var coords = "X coords: " + x + ", Y coords: " + y;
  //alert(isDrawing);
}

The code is failing to find myPics = document.getElementById('myPics'); the canvas in the HTML is coming out with the ID as myPics, but I don't think the JavaScript is getting the element.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132

2 Answers2

0

I would recommend using useRef to access DOM elements:

function CanvasElement() {
    const canvasEl = useRef(null);
    
    return (
        <canvas ref={ canvasEl }></canvas>
    );
}

Then you can access the DOM element using canvasEl.current:

canvasEl.current.getContext('2d');

See also: How to access a DOM element in React?

Phil
  • 1,849
  • 4
  • 24
  • 38
  • This is how I genereate my canvas to get a better idea of what im working with thanks wp.element.createElement( wp.blockEditor.RichText.Content, { tagName: 'canvas', id: 'canvas', width: '560', height: '360', onClick: imgclickHandler, onMouseMove: imgclickDrawHandler, onMouseUp: imgOffclickHandler } – Aneuroo May 21 '21 at 17:55
0

This works as it should and get the context to the correct place

    function canvasonclickHandler(event) {
          canvas = document.getElementById("canvas");
          context = canvas.getContext("2d");
          rect =canvas.getBoundingClientRect();
          xset = event.clientX - rect.left;;
          yset = event.clientY - rect.top;
          isDrawing = true;
          //alert("x: "+ x +"y: "+ y);

    }