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>