I have the following lines of code, if I put the block of code into body tag it works, but when I tried to put it into the header, it does not work.
<script type="application/javascript" language="JavaScript">
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top};
}
var canvas = document.getElementById("canvas_prime");
var context = canvas.getContext("2d");
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
</script>
I'm guessing its because the addeventlistener
is not triggered when it's in the <head>
, how to fix it? thanks.
You can't bind the event handlers until you can get the elements you want to bind to, and you can't do that until they exist.
For example:
addEventListener('load', bindEventHandlers);
function bindEventHandlers() {
var canvas = document.getElementById("canvas_prime");
var context = canvas.getContext("2d");
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.