Reputation: 19
I want something to happen in p5js when the mouse is over a map of a country (which is not a standard shape). How can I do that? I mean how can I track a mouse on a non-standard shape like the map of a country?
(I've loaded this shape as an image and the spots out of the borders are still part of the image but are transparent. )
Thanks
Upvotes: 1
Views: 1139
Reputation: 42174
There are a few ways to do this:
createShape()
method instead.If I were you, I would lean towards the first option. Get something simple working first: create a hard-coded shape, and then create a sketch that prints a message to the console when the mouse clicks inside that shape. Then get the geometry for the country and use that instead of the hard-coded shape.
Then if you get stuck, you can post a MCVE along with a more specific technical question. Good luck.
Upvotes: 1
Reputation: 155578
Rather than going through effort to track the mouse and perform your own colission-detection, why not go old-school and use <map>
and <area>
?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area
The HTML
<area>
element defines a hot-spot region on an image, and optionally associates it with a hypertext link. This element is used only within a<map>
element.The HTML
<map>
element is used with elements to define an image map (a clickable link area).
<area>
is represented in the DOM by HTMLAreaElement
which implements the HTMLElement
interface so you can listen to mouseover
events coming from the <area>
elements:
Example HTML (from the MDN article):
<map name="infographic" id="myInfographic">
<area shape="rect" coords="184,6,253,27"
href="https://mozilla.org"
target="_blank" alt="Mozilla" />
<area shape="circle" coords="130,136,60"
href="https://developer.mozilla.org/"
target="_blank" alt="MDN" />
<area shape="poly" coords="130,6,253,96,223,106,130,39"
href="https://developer.mozilla.org/docs/Web/Guide/Graphics"
target="_blank" alt="Graphics" />
<area shape="poly" coords="253,96,207,241,189,217,223,103"
href="https://developer.mozilla.org/docs/Web/HTML"
target="_blank" alt="HTML" />
<area shape="poly" coords="207,241,54,241,72,217,189,217"
href="https://developer.mozilla.org/docs/Web/JavaScript"
target="_blank" alt="JavaScript" />
<area shape="poly" coords="54,241,6,97,36,107,72,217"
href="https://developer.mozilla.org/docs/Web/API"
target="_blank" alt="Web APIs" />
<area shape="poly" coords="6,97,130,6,130,39,36,107"
href="https://developer.mozilla.org/docs/Web/CSS"
target="_blank" alt="CSS" />
</map>
<img usemap="#infographic" src="/media/examples/mdn-info.png" alt="MDN infographic" />
Script:
var areas = document.querySelectorAll( '#myInfographic area' );
for( var i = 0; i < areas.length; i++ ) {
areas[i].addEventListener( 'mouseover', function( e ) {
console.log( 'over some area' );
} );
}
Upvotes: 0