2011-10-01 2 views
0

캔버스에 웨이브 애니메이션을 만들려고하는데 정말 느리게 작동합니다 (아마도 나쁜 코드 때문일 것입니다).
이 작업을 더 원활하게 만들고 Wave (Math.sin)을 바다 물결처럼 보이게 만들 수 있습니까?HTML5 캔버스 | 이 작품을 더 부드럽고 더 좋게 만들려면 어떻게해야합니까?

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

내가 코드를 꽤 변경 jQuery를 위해 종속성을 제거 :
다음은 코드입니다. 그러나 내가 코드 속도를 높이기 위해 수행 한 주요 작업은 draw 작업 이후에 한 번만 호출되도록 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; 
} 
+0

와우 멋진 작품!하지만 지금은 더 파도처럼 사인 모양을 만들 수있는 방법? 너비가 넓어 지도록하고 싶다. – funerr

관련 문제