Snow via Javascript & Canvas – Tis the Season

    After playing with the settings in my experiments I found a few settings I liked and wanted to develop further. The first was snow! An added bonus I was able to work on a project just for the holidays and used much of this code in it! I looked around the web and saw a couple interesting examples of snow, but nothing that stood out to me. I used couple images and pulled them into the canvas in place of the dot (choosing one of 3 flake graphics), and learned how to apply a rotation to that graphic from somewhere online (I think stackoverflow, but now I can’t find it again to link it. The physics settings are hardcoded now and the update function doesn’t check the dot y position against the top of the page, since the snow should all be moving down with the gravity, it could be moved up with it’s floating, but I just wanted it to come down on it’s own. Then to get the rotation we need to save the context state, more to the flake center, rotate it and then move back to the canvas origin, draw the image and restore context. This process sounded complicated and took a bit to get things in the right order and the whole time I was scared it would be too processor intense for a good amount of snowflakes, it seems to do just fine! interactive physics animations via javascript & canvas | snow application example: check it out!

    $(function () {
        var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
        var total_dots = 150;
        var fps = 24;
       
        canvas = $("#canvas")[0];
        context = canvas.getContext("2d");
        var dots = new Array();
        var drag_i = -1;
        var gravity = .05;
        var friction = .98;
        var bounce = -.96;
        var wrap = true;
        var float = true;
       
        var imgs = new Array();
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();
        img1.src = "snowflake_1.png";
        img2.src = "snowflake_2.png";
        img3.src = "snowflake_3.png";
        imgs[0] = img1;
        imgs[1] = img2;
        imgs[2] = img3;
        var this_dot = {};
        for (var i=0; i < total_dots; i++){
            createDot();
        }
        function createDot(x, y, r, vx, vy){
            var this_dot = {
                x:      typeof(x) != 'undefined' ? x : Math.random()*canvas.width,
                y:      typeof(y) != 'undefined' ? y : Math.random()*-canvas.height,
                radius: typeof(r) != 'undefined' ? r : 25,
                scale:  Math.floor(10 + (1+50-10)*Math.random()),
                vx:     typeof(vx) != 'undefined' ? vx : Math.random()*3-1,
                vy:     typeof(vy) != 'undefined' ? vy : Math.random()*3,
                //this will pick a digit 1, 2 or 3 and set it as the src value, this could also be a Math.floor(Math.random()*3)+1 to really be random
                src:    (dots.length % 3) + 1,
                r:      0,
                vr:     0
            };
            dots.push(this_dot);
        }
       
        draw();
       
        $("#canvas").mousedown(function (event) {
            createDot(event.pageX - this.offsetLeft-25, event.pageY - this.offsetTop-25);
        });
       
     
        $("#canvas").mouseup(function (event) {
            drag = false;
            drag_i = -1;
        });
       
        function update(){
            for (var i=0; i < dots.length; i++){
                if (drag_i != i){
                    var this_dot = dots[i];
                    if (float){
                        this_dot.vx += Math.random() - .5;
                        this_dot.vy += Math.random() - .5;
                        this_dot.vr += Math.random()*.01 - .005;
                    }
                    this_dot.vx *= friction;
                    this_dot.vy = this_dot.vy * friction + gravity;
                    this_dot.x += this_dot.vx;
                    this_dot.y += this_dot.vy;
                    this_dot.r += this_dot.vr;
                   
                        if (this_dot.x > canvas.width + this_dot.radius){
                                this_dot.x -= canvas.width + this_dot.radius*2;
                                this_dot.vr = 0;
                        }
                        else if(this_dot.x < 0 - this_dot.radius){
                                this_dot.x += canvas.width + this_dot.radius*2;
                                this_dot.vr = 0;
                        }
                        if (this_dot.y > canvas.height + this_dot.radius){
                                this_dot.y -= canvas.height + this_dot.radius*2;
                                this_dot.vr = 0;
                        }
                   
                }
            }
        }
        function draw() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            for (var i=0; i < dots.length; i++){
                var src = img1;
                if (dots[i].src == 1){  }
                else if (dots[i].src == 2){ src = img2; }
                else { src = img3; }
                context.save();
                context.translate(dots[i].x+dots[i].scale/2, dots[i].y+dots[i].scale/2);
                context.rotate(dots[i].r);
                context.translate(-dots[i].x-dots[i].scale/2, -dots[i].y-dots[i].scale/2);
                context.drawImage(src, dots[i].x, dots[i].y, dots[i].scale, dots[i].scale);
                context.restore();
            }
        }
       
        setInterval(function() {
            update();
            draw();
        }, 1000/fps);
       
    });

    Follow the whole Interactive Physics Animations via Javascript & Canvas series.

    This entry was posted in interactive javascript canvas and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      Touch Specific Media Queries in CSS4

      Proposals in the works for new media queries specific to touch enabled devices. Examples include pointer, which will differentiate wether the device has a fine or coarse pointer (finger vs mouse) and hover, which would say if the device supports hover states. I can see this being helpful and useful for building mobile friendly sites [...]

      Responsive Image Dispute and Tourists – Analogy

      Jason explains the root of the problem and why no one has been able to devise a solution that makes everyone happy yet. The browsers (in their awesome drive to make browsing faster) are prefetching images and developers want to only use one image based on criteria the browser doesn't know until the layout is [...]

      Google Moog Keyboard Synthesizer Detailed

      This post on creativejs picks apart how this doodlue was made. Nice they they are able to support HTML5 audio even if it is only supported on chrome and the rest fall back to – you guessed it – flash. Embedded Link Google Moog synth tear-down Yesterday we featured Google's web-based analogue synth Moog tribute [...]

      Synth Emulator on Google Japan Doodle Today

      Synth Emulator on Google Japan Doodle Today Embedded Link Moog 自分のオリジナル曲を創って、 #moogdoodle で共有しよう。 Tweet

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...