开发者

Are all mouse draggable objects in HTML5 canvas based on setInterval?

I am making a geometrical optics demo in HTML5 canvas, the mouse points the light source, you can craft some barriers, javascript do the calculation work and display light and shadow on on a line behind those barriers.

from those canvas drag'n'drop tutorials I found online, all of them are using setInterval() to make mouse interactions happen, which means the whole canvas is updated and re-painted all the time. This makes me feel the whole canvas business is an ugly hack.

My question is: are there any other way to make mouse interactions in canvas without the setInterval() way? I want to paint the background once and only red开发者_如何学编程raw the moving part while onmousemove when the mouse is actually moving.

Any idea is appreciated. Thanks :)


You can redraw the canvas without the element being dragged, then draw the element to a new canas on top of the base. Then you can use absolute positioning to move the one being dragged without any redrawing.


There is a mousemove available on the canvas element. I use it all the time and i believe it is very useful in your situation.

You could also do it with setInterva but that's sounds kind of dirty to me in this case. You need to get the mouse X and Y anyway, what beter place to do that in the mousemove event!


Look at that article: http://www.splashnology.com/article/fifteen-puzzle-in-libcanvas/1632/

There are some ways to optimize canvas drawing. First of all - not redraw full canvas, only changed parts. And redraw only if something changed.

At work I create game based on LibCanvas now and background I draw at another layer. Something like that:

var libcanvas  = new LibCanvas( 'canvas' ).start();
var background = libcanvas.createLayer( 'bg', 0 );
drawBackgroundAt  ( background );
startApplicationAt( libcanvas );


First draw the background, then save the canvas with canvas.save().

On mouse interaction: canvas.restore() and draw your drawings.


I think what you are experiencing is that you need setInterval to update the canvas everytime you do mouseinteraction. And that feels a bit ugly to you because that's seems to you like "Hacking".

You don't have to feel bad about it, because you will need that mechanism for anything that should be animated.

But you can do "clipping" in the method you call through setInterval you could decide which part of your canvas should be updated and only redraw that part.

If you don't need constantly updating your content, because its not animated i agree to Elmer.

But updating the canvas through setInterval is neither ugly nor dirty ;-) It's the way you keep canvas updated if you want to animate something.


I have to finish this question, the answer should be requestAnimationFrame from pimvdb

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜