HTML5画布|如何让这项工作更顺畅,更好?

时间:2011-10-01 13:09:06

标签: performance html5 canvas

我正在尝试在画布中创建一个波形动画,但它的工作速度非常慢(可能是因为代码错误)。
如何让这项工作更顺畅,让Wave(Math.sin)看起来更像海浪? 这是代码:

<!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>

1 个答案:

答案 0 :(得分:1)

我更改了代码,删除了jQuery的依赖项。然而,我为加速你的代码所做的主要工作是在绘制操作之后仅移动fill一次,并开始/结束路径的绘制。此外,我对回忆resizeCanvas()感到困惑,我只想将其与window.onresize事件联系起来,并将画布设置为窗口的innerwidth / innerheight

<强> 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;
}