开发者

HTML5 Canvas | How can I make this work smoother and better?

I am trying to create a wave animation in my canvas, but it works really slowly (Probably because of开发者_开发百科 bad code).

How can I make this work smoother, and make the Wave(Math.sin) look more like a sea wave?

Here is the code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML 5 site</title>
        <style>
        #canvas{
        margin:0 auto;
        }
        *{
        overflow:hidden;
        }
        </style>
        <script src="jquery-1.6.4.min.js"></script>
    </head>
    <body>
    <div id="warp">
    <canvas id="canvas" style="border:1px solid black;" />
    Your Browser does not support HTML5;
    </canvas>
    </div>
    <script>
    $(document).ready(function(){
    resizeCanvas();
    function resizeCanvas() {
    $("#canvas")
        .attr('width', $(window).width())
        .attr('height', $(window).height());
    }

    $(window).resize(resizeCanvas());
        x=0;y=0;
        var ctx = $("#canvas").get(0).getContext('2d');
        $('#canvas').mousemove(function(e){
        resizeCanvas();
        for(var i=0;i<=$(window).width();i++){
            y =Math.sin((i+x)*50)*12;
            ctx.fillStyle = "blue";
            ctx.arc(i, y+100, 4, 0, 2*Math.PI);
            ctx.fill();
            }
            x+=20;
        });
    });
    </script>
    </body>
</html>


I changed the code quite a bit, removed the dependency for jQuery. The main thing however that I did to speed up your code was move the fill to be called only once after the draw operations, and start/end the drawing of the path. Also I was confused by the recalling of resizeCanvas() I would just tie that to the window.onresize event and just set the canvas to the innerwidth/innerheight of the window.

Live Demo

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x=0,y=0;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;


canvas.onmousemove= function(e){
    //clear the canvas
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.fillStyle = "blue";

    var width = window.innerWidth;

    // start the path
    ctx.beginPath();
    //draw it
    for(var i=0;i<=width;i++){
        y=Math.sin((i+x)*50)*12;
        ctx.arc(i, y+100, 4, 0, 2*Math.PI);
    }
    //close it
    ctx.closePath();
    //fill it
    ctx.fill(); 
    x+=20;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜