0

I am new to coding (in general), and I'm trying to make a button inside a canvas. When I save the code and open up the canvas, it is blank. I open up the sources, and I find that there is an "Uncaught TypeError: Cannot Read Property 'getContext' of Null. I think I am missing something in the window.onload function, but I do not know what to put there. I have tried: window.onload = function() { createGetContext }, but that did not work.

<html>

    <script>

window.onload = function() {
// I do not know what to put here
//    ???
}

function getMousePos(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}
//Function to check whether a point is inside a rectangle
function isInside(pos, rect){
    return pos.x > rect.x && pos.x < rect.x+rect.width && pos.y < rect.y+rect.height && pos.y > rect.y
}

var canvas = document.getElementById('myCanvas');

//THIS LINE
//this code cannot be read properly
var context = canvas.getContext('2d');

//The rectangle should have x,y,width,height properties
var rect = {
    x:250,
    y:350,
    width:200,
    height:100
};
//Binding the click event on the canvas
canvas.addEventListener('click', function(evt) {
    var mousePos = getMousePos(canvas, evt);

    if (isInside(mousePos,rect)) {
        alert('clicked inside rect');
    }else{
        alert('clicked outside rect');
    }   
}, false);


</script>

</html>
  • Is that all your code? Most likely, you are missing a `canvas` element in your HTML with the id `myCanvas`. Thus, `document.getElementById('myCanvas')` is null. Add `` inside your `` just before ` – ffritz Jun 30 '20 at 14:33
  • What variable is it that you try to call `.getContext()` on? Where does the content for that variable come from? In what cases does that method return `null`? Combine it all and you should find the answer to `// I do not know what to put here ???` – Andreas Jun 30 '20 at 14:38
  • you need to put all that code in the load callback. – Daniel A. White Jun 30 '20 at 14:43

0 Answers0