简体   繁体   中英

Changing colors of shapes in HTML5 canvas

I'm working on displaying interactive map in html5.

I have created zones of map as array of numbers (representing coordinates) like:

Zone1=[{x=3,y=4}, {x=8,y=5}]

and I have also created a map which is an array of zones like:

map=[zone1, zone2....]

I have no problem drawing the zones in the canvas using context.lineTo() function, the same way I'm able to capture the mouse position on click and determine on which zone a user has clicked using point in polygon algorithm.

My difficulty arises when I want to fill color of of the zone when it is clicked at.

Anybody have ideas?

PS:

  • The shapes I made are irregular
  • I'm not in to using JavaScript libraries like jQuery or anything else

HTML5 Canvas does not know of notion of shapes of objects which you can manipulate. You have two options in your situation:

  • Use SVG to draw what you need ( check examples on W3Schools )
  • Use some JS canvas library which adds abstraction to provide notion of shapes (check out EasleJS )
  • Write your own abstraction over canvas to provide shapes

You should know however, that even with such libraries, "shapes" are getting fully redrawn. Possibly, entire scenes are redrawn. SVG alleviates this, it's performance decreases as number of shapes/objects grows.

You can't. The shapes you created are not variables or referenceable in any way once they are added to the canvas. You could redraw the shape with a new colour over the old one, but I think your best bet would be to use a library to handle this for you.

Since I have used it myself, my own suggestion would be Kinetic.js, but there are a plenty to chose from.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM