davej Posted May 2, 2018 Share Posted May 2, 2018 If you have a canvas and you want to have some number of visible images on it with mouseover events (or the equivalent) for each image what is the most efficient approach to accomplish this? Is it possible to use the images in some manner with mouseover events? Or must I simply use the mousemove event and keep checking the mouse coordinates? Thanks. Link to comment Share on other sites More sharing options...
davej Posted May 2, 2018 Author Share Posted May 2, 2018 I am leaning toward positioning the images under the canvas and positioning matching divs over the canvas. That way the images are protected and the mouseover events can be assigned to the divs. <!DOCTYPE html> <html lang="en"> <head> <meta charset='utf-8'> <title>MouseOver Event on Canvas</title> <style> #container{ z-index: 0; position: relative; height:700px; width:700px; background-color: pink; } #myCanvas { z-index: 10; border: #333 10px solid; position: absolute; top: 50px; left: 40px; height: 600px; width: 600px; } #squ1 { /* opacity:0; */ border: 1px solid red; z-index: 20; position: absolute; top: 100px; left: 100px; height: 100px; width: 100px; } #squ2 { /* opacity:0; */ border: 1px solid blue; z-index: 20; position: absolute; top: 500px; left: 500px; height: 100px; width: 100px; } #pic1{ z-index: 1; position: absolute; top: 100px; left: 100px; height: 100px; width: 100px; } #pic2{ z-index: 1; position: absolute; top: 500px; left: 500px; height: 100px; width: 100px; } </style> </head> <body> <div id="container"> <div id="squ1"></div> <div id="squ2"></div> <canvas id="myCanvas"></canvas> <image id="pic1" alt="1"/> <image id="pic2" alt="2"/> </div> <script> document.getElementById('squ1').addEventListener('mouseover',squ1over,false); document.getElementById('squ2').addEventListener('mouseover',squ2over,false); var src1 = "https://uploads.guim.co.uk/2017/10/06/First-Dog-on-the-Moon,_L.png"; var src2 = "https://image.freepik.com/free-vector/cheese-cartoon_22350-100.jpg"; var img1 = document.getElementById('pic1'); var img2 = document.getElementById('pic2'); img1.src = src1; img2.src = src2; var canvas = document.getElementById('myCanvas'); function squ1over(){ alert('squ1 touched'); } function squ2over(){ alert('squ2 touched'); } </script> </body> </html> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now