dcsimg
www.webdeveloper.com
Results 1 to 6 of 6

Thread: Better way to set width?

  1. #1
    Join Date
    May 2012
    Posts
    16

    Better way to set width?

    Is there a more efficient way of setting the width of DOM elements like this? The code is running at 60fps and the framerate is pretty much up and down. Should I use Canvas for this or is there a better way?

    JavaScript code:
    Code:
    var value = 50,
         bar = document.getElementById('bar').style;
    
    function loop() {
    Math.random() < 0.5 ? value += 3 : value -= 7;
    bar.width = value + "%"
    setTimeout(loop,16); // run at 60 fps
    }
    
    loop();
    HTML code:
    HTML Code:
    <div id="bar"></div>

  2. #2
    Join Date
    Dec 2012
    Posts
    196
    Using requestAnimationFrame might make things a little smoother

    HTML Code:
    <script>
    window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
    
    var value = 50,
         bar = document.getElementById('bar').style;
    
    function loop() {
        Math.random() < 0.5 ? value += 3 : value -= 7;
        bar.width = value + "%"
        window.requestAnimationFrame(loop);
    }
    
    loop();
    </script>  

  3. #3
    Join Date
    May 2012
    Posts
    16
    I tried it, but the the same performance drop pretty much. Do you think making this in Canvas is better?

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,585
    Word of note... You can not set a frames per second nor can you create a way of making it appear to run at a desired frames per second.

    The reason is that each computer you run the script on will not run at the same speed. A 3 Ghz processor is faster than a 2 Ghz processor by a factor of 50% or a 1/3rd slower, either way you can not factor in a test for speed.

    You could use the CSS3 transition methods, plenty of examples out on the net for that method.
    If your post falls off the page, bump it. ...
    Please remember to wrap any code you have in forum tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  5. #5
    Join Date
    May 2012
    Posts
    16
    But how can I use CSS3 transitions for this? It's only setting the width.

  6. #6
    Join Date
    Mar 2014
    Posts
    24
    With the help of properties of the page then we can change the width of any thing......

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles