Tyler
Tyler

Reputation: 3813

Movement in html5 canvas

I am trying to figure out the right way to do movement in canvas. From my research it appears that a lot of tutorials use redrawing. I got movement to work by clearing my shapes and recreating them (redrawing?): http://pastebin.com/VuYdtM2U

I am wondering though if that is the way it is supposed to be done or if there is a better way. I can imagine clearing an image and creating it a pixel over every fraction of a second would get resource intensive.

Upvotes: 1

Views: 120

Answers (2)

Sukrit Gupta
Sukrit Gupta

Reputation: 448

Generally, It is done this way only. Most of the Browser Games are coded this way and a lot of clearing and re rendering takes place seamlessly. Modern Browsers can handle a lot of rendering without any delay.

The main reason behind this is that, Canvas is just a sort of image for the browser and it just draws on it and don't have to retain any Element DOM Structure.

Whereas in case of SVG, all elements have to be appended / deleted /added to the DOM Structure which takes toll if there are a lot of elements.

There are several factors which can help us decide which technique is better as per the case.

Generally for Page with DOM elements less than 10,000... Both are efficient.

You can also use mixture of Canvas , SVG and Multiple Canvas (like you may want to show a hover canvas, over another canvas)..

Upvotes: 3

Mr. A
Mr. A

Reputation: 1231

Try this

    
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height=400 width=500>
<g>
<rect transform="translate(-20,-20)" height="40" width="40" style="fill:#777; stroke:none;"/>
<animateMotion fill="freeze" path="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" dur="3.14159s" repeatCount="indefinite"/>
</g>
<path d="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" style="fill:none;stroke:#F00;stroke-width:5"/>
</svg>

Upvotes: 1

Related Questions