简体   繁体   English

更改HTML5画布中形状的颜色

[英]Changing colors of shapes in HTML5 canvas

I'm working on displaying interactive map in html5. 我正在研究在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. 我没有问题可以使用context.lineTo()函数在画布上绘制区域,这与我能够捕获单击时鼠标位置并使用多边形算法中的点确定用户单击的区域相同。

My difficulty arises when I want to fill color of of the zone when it is clicked at. 当我想在单击区域时填充区域的颜色时,就会出现困难。

Anybody have ideas? 有人有想法吗?

PS: PS:

  • The shapes I made are irregular 我做的形状不规则
  • I'm not in to using JavaScript libraries like jQuery or anything else 我不喜欢使用jQuery等JavaScript库

HTML5 Canvas does not know of notion of shapes of objects which you can manipulate. HTML5 Canvas不了解您可以操纵的对象形状的概念。 You have two options in your situation: 您有两种选择:

  • Use SVG to draw what you need ( check examples on W3Schools ) 使用SVG绘制所需的内容( 在W3Schools上 查看示例
  • Use some JS canvas library which adds abstraction to provide notion of shapes (check out EasleJS ) 使用一些JS画布库,该库添加了抽象以提供形状的概念(请查看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. SVG可以缓解这种情况,随着形状/对象数量的增加,其性能会降低。

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. 由于我自己使用过,因此我的建议是Kinetic.js,但是有很多可供选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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