I am sort of new here and new to javascript. i am trying to learn how to work JavaScript/html5/canvas. I have been working my way through several tutorials. I have gone trough the ones about animating a shape but can not find a good one yet where a drawn shape reacts to user input. Like a mouse going over a rectangle resulting in a color change. Or even better eventually something like this.
http://dan.forys.co.uk/experimen开发者_高级运维ts/mesmerizer/
can anyone one point me to a good tutorial to achieve that? thank you Daniela
First to clarify one thing, the canvas itself doesn't know very much about what's on it. It can tell you what color a pixel is but it can't tell you a rectangle is here or a circle is there. For our purposed, consider the canvas to be write-only. Functionality like that exists in SVG if you want to consider it for your application, with the caveat that the canvas is more universally supported.
Knowing what's under the mouse really relates to what your application is. In the example you posted, the developer took the X and Y position from the mouse event (using jQuery) and did some quick math to calculate what row and column you were in. They could then apply that to an saying, "cell (x, y) was just moused over, when you do the next redraw consider that."
Canvas applications generally work the following way:
- Create an environment entirely in JavaScript (with arrays, objects, etc).
- Use a rendering routine to draw the environment to the canvas.
- Listen for mouse events, timers, etc.
- Check how the event affects the environment.
- Apply changes to the environment.
- Reuse the rendering routine from step 2 to update the canvas with the new environment.
- Go to step 3.
With that in mind, any tutorial should be helpful, be it for Java, .Net, Android, etc. They all have their own drawing surfaces and tutorials that build on them.
In regards to the canvas, here's a fun tutorial: http://billmill.org/static/canvastutorial/index.html
The tutorial builds a breakout game which listens to mouse events and timer events. The mouse event doesn't do any checking to see what its over, but the timer event does some work to check if the ball exists in the same space as a block or the paddle and updates the canvas and the JavaScript environment accordingly.
精彩评论