I'm trying to add events to an Image object, which I create dynamically (using the Image() constructor) and bind to a HTML canvas element. I have successfully added the "load" event. However, I can't add any other events, such as "click" or "mousedown". The Javascript and HTML code blocks are pasted below.
The "load" event handler is called and I get the alert. However, the "mousedown" event is not. Why do I see this behaviour and how can I correct it?
Many thanks for your help.
ps: The "mouseup" event on element works fine.
function myDraw(){
var img = new Image(); // Create new img element
img.addEventListener('load', function() {
alert('Loaded! img type is \n' + typeof img);
// execute drawImage statements here
const canvas = document.getElementById('canvas');
canvas.setAttribute('width', 1000);
canvas.setAttribute('height', 1000);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 200,200);
}, false);
img.src = './floorplan.jpg'; // Set source path
img.addEventListener("mousedown",function(){
alert('Mouse down');
}, false);
const c1 = document.getElementById('h1');
c1.addEventListener('mouseup',function(){
alert('Mouse up');
}, false);
}
myDraw();
<div>
<h1 id="h1">CANVAS</h1>
<canvas id="canvas"></canvas>
<!--img id="fplan" src = "./floorplan.jpg" /-->
</div>
<script src='./script.js' type="text/javascript"></script>
It seems that I needed to add the event listener to the canvas element and not the image loaded on to the canvas.
The c1.addEventListener('click',clickZoom, false); line achieves this.
const c1 = document.getElementById('canvas');
c1.setAttribute('width', 1000);
c1.setAttribute('height', 1000);
const ctx = c1.getContext('2d');
var img = new Image(); // Create new img element
function myDraw(){
img.addEventListener('load', function() {
// execute drawImage statements here
ctx.drawImage(img, 200,200);
}, false);
img.src = './floorplan.jpg'; // Set source path
c1.addEventListener('click',clickZoom, false);
}
function clickZoom() {
alert('Zoom clicked');
ctx.drawImage(img, 200, 200, ctx.canvas.width * 0.5, ctx.canvas.height * 0.5); // this needs changing wrt image size not canvas size!!
}
myDraw();
<div>
<h1 id="h1">CANVAS</h1>
<canvas id="canvas"></canvas>
<!--img id="fplan" src = "./floorplan.jpg" /-->
</div>
<script src='./script.js' type="text/javascript"></script>