0

저는이 문제를 며칠 동안 보았습니다. 저는 처음으로 생성자 패턴에 코드를 작성했습니다. 전환시 10 개의 베 지어 라인의 높이를 확장하고 싶습니다. 나는 kineticjs (i failed)를 시도하고, Setinterval 애니메이션에서 멍청이를 만듭니다.) 그래서 결국 애니메이션 프레임을 요청했습니다. 그러나이 생성자 패턴으로 인해, 나는 그것을 어디에 넣고 변경해야하는지 완전히 혼란 스럽습니다. 다음 패턴을 따르는 코드에서 요청 애니메이션 프레임을 사용하는 방법은 무엇입니까?

내가 모든 베 지어 라인의 높이를주는 전환 증가한다 그래서 기본적으로 나는 캔버스의 transition.Onmouseover 내 앤디와 cpY1 및 cpy2 연장됩니다 --- 지금까지 JSFIDDLE

했을 것입니다 느낌 같은 애니메이션.

JAVASCRIPT : 여기

//for entire code please have a look at the fiddle.this is just 10% of my code 
//for simplification purpose,you can use 3 instances instead of 9!!! 
    (function() { 
     hair = function() { 
      return this; 
     }; 


    hair.prototype={ 

    draw_hair:function(a,b,c,d,e,f,g,h){ 

      var sx =136+a;//start position of curve.used in moveTo(sx,sy) 
      var sy =235+b; 
      var cp1x=136+c;//control point 1 
      var cp1y=222+d; 
      var cp2x=136+e;//control point 2 
      var cp2y=222+f; 
      var endx=136+g;//end points 
      var endy=210+h; 

     var canvas = document.getElementById('myCanvas'); 
     var context = canvas.getContext('2d'); 
     context.strokeStyle="grey"; 
     context.lineWidth="8"; 
     context.beginPath(); 
     context.moveTo(sx,sy); 
     context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,endx,endy); 
     context.lineCap = 'round'; 
     context.stroke(); 
    } 
}; 
})(); 
+0

나는 코드를 가져 와서 생성자가있는 Hair "클래스"버전을 만들었습니다. 이 클래스에 필요한 털의 수를 입력하고 필요에 따라 모든 털을 그룹으로 그리거나 다시 그립니다. mousemove 핸들러는 9 개의 개별 객체 대신 하나의 그룹에만 응답해야하기 때문에 성능 향상을 위해이 작업을 수행했습니다. 나는 또한 머리카락을 자라게하는 클래스의 메서드를 추가했습니다. 앞서 설명한 것처럼 제어점과 끝점의 "Y"좌표를 높이면됩니다. 프로젝트에 행운을 빈다. :) – markE

+0

@markE : 내가 성장한 머리카락을 넘을 순간, 그들은 짧아 져서 바람직하지 않다 ...하지만 괜찮아 ... 나는 여기에서 계속 될 것이다. 감사 마크 !!! 심각하지만 ... 작다. 질문과는 별도로, 56 세의 나이에 당신을 계속 지킵니다 !!! # 존경 –

+1

나는 매일 새로운 것을 배울 때 가장 행복합니다. 지금까지 인생은 배우기에 충분한 재미있는 것들을 제공했습니다! – markE

답변

0

는 머리를 성장에 대해 원하는 답변입니다.

머리카락을 "개체"로 만드는 방법에 대한 정보도 있습니다.

코드와 바이올린 : http://jsfiddle.net/m1erickson/8K825/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    window.requestAnimationFrame = (function(callback) { 
     return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || 
     function(callback) { 
     window.setTimeout(callback, 1000/60); 
     }; 
    })(); 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 

    var canvasOffset=$("#canvas").offset(); 
    var offsetX=canvasOffset.left; 
    var offsetY=canvasOffset.top; 

    // the Hair "object" 
    // Hair is a containing object that hosts a user-specified # of hairs 
    var Hair = (function() { 

     // constructor 
     function Hair(x,y,width,height,haircount) { 

      this.x=x; 
      this.y=y; 
      this.width=width; 
      this.height=height; 
      this.right=this.x+this.width; 
      this.bottom=this.y+this.height; 
      this.hairCount=haircount; 
      this.startX=x+20; 
      this.startY=y+height-3; //235; 
      this.hairHeight=25; 
      this.hairGrowth=0; 
      this.lastEndX=[]; 

      for(var i=0;i<haircount;i++){ 
       this.lastEndX[i]= x+20+(i*15); 
      } 

     } 
     // grows the hair 
     // works by changing the Y value of the end & control points 
     Hair.prototype.grow = function(increment){ 
      this.hairGrowth+=increment; 
      return(this.hairGrowth); 
     } 
     // draw all the hairs 
     Hair.prototype.draw = function(mouseX){ 

      // clear this object's space on the canvas 
      // and set its styles 
      ctx.clearRect(this.x,this.y,this.width,this.height); 
      ctx.beginPath(); 
      ctx.strokeStyle="grey"; 
      ctx.lineWidth=7; 
      ctx.lineCap = 'round'; 
      ctx.beginPath(); 

      for(var i=0;i<this.hairCount;i++){ 

       // straight hair 
       var sx=cp1x=cp2x= this.startX+(i*15); 
       var sy= this.startY; 
       var cp1y = cp2y = (this.startY-(this.hairHeight+this.hairGrowth)/2); 
       var endy = this.startY-this.hairHeight-this.hairGrowth; 
       var endx = this.lastEndX[i]; 

       // create bend, if any 
       if(Math.abs(mouseX-sx)<=10){ 
        endx = sx+(mouseX-sx)*1.1; 
        this.lastEndX[i]=endx; 
       }; 

       // draw this curve 
       ctx.moveTo(sx,sy); 
       ctx.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,endx,endy); 

      } 
      // stroke 
      ctx.stroke(); 
      // temp outline 
      ctx.lineWidth=1; 
      ctx.beginPath(); 
      ctx.rect(this.x,this.y,this.width,this.height); 
      ctx.stroke(); 
     } 
     // 
     return Hair; 
    })(); 


    var direction=1; 
    var fps = 3; 
    function animate() { 
     setTimeout(function() { 

      // change hair length 
      var hairLength=hair.grow(direction); 
      if(hairLength<1 || hairLength>10){ direction=(-direction); } 

      // draw 
      hair.draw(); 

      // request next frame 
      requestAnimationFrame(animate); 

     }, 1000/fps); 
    } 


    function handleMouseMove(e){ 
     mouseX=parseInt(e.clientX-offsetX); 
     mouseY=parseInt(e.clientY-offsetY); 
     $("#movelog").html("Move: "+ mouseX + "/" + mouseY); 

     // Put your mousemove stuff here 
     if(mouseX>=hair.x && mouseX<=hair.right && mouseY>=hair.y && mouseY<=hair.bottom){ 
      hair.draw(mouseX); 
     } 
    } 

    $("#canvas").mousemove(function(e){handleMouseMove(e);}); 

    $("#grow").click(function(e){ animate(); }); 

    // create a new patch of hair 
    var hair=new Hair(25,50,150,50,8); 
    hair.draw(225); 


}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <p id="movelog">Move</p> 
    <canvas id="canvas" width=300 height=200></canvas><br> 
    <button id="grow">Grow Hair</button> 
</body> 
</html> 

[추가 : "클래스"의 설명과 클래스에서 객체를 인스턴스화]

var Hair=(function(){ …; return Hair; })()는 헤어 "클래스"를 생성합니다.

var hair = new Hair(…)은 실제 사용 가능한 모발 "개체"를 만듭니다.

헤어 클래스를 템플릿 (또는 청사진 또는 쿠키 커터)으로 생각하십시오. Hair 클래스의 모든 코드는 클래스의 속성과 메서드 만 정의합니다. 실제로 Hair 클래스의 코드는 호출하지 않습니다. 실제 머리 객체를 생성하기위한 템플릿으로 사용하기 만하면됩니다.

Hair 클래스를 사용하면 재사용 할 수있는만큼 실제 머리 개체를 만들 수 있습니다. 머리 개체를 만드는 행위를 "머리 종류의 인스턴스화"라고합니다.

사실, javascript에는 실제로 클래스가 없으므로 이것은 단지 의사 클래스입니다. 그러나 그것은 완전히 다른 설명입니다!

질문 : 방향 = 0.25의 용도는 무엇입니까?

방향 변수는 머리카락이 애니메이션 중에 "커지는"경우 머리카락 높이를 점차적으로 늘리는 데 사용됩니다. .25는 머리카락의 컨트롤/끝점에 애니메이션 프레임 당 .25 픽셀 씩 올라간다는 것을 알려줍니다.

질문 : 콜백 기능과 그 settimeout의 의미는 무엇입니까?

setTimeout은 애니메이션이 초당 고정 된 프레임으로 발생하도록 requestAnimationFrame을 래핑합니다.

RequestAnimationFrame (RAF)은 성능을 최적화하는 훌륭한 작업이지만 RAF만으로는 초당 프레임 수를 제어 할 수 없습니다. setTimeout 안에 RAF를 래핑하면 초당 프레임 수를 제어 할 수 있습니다. 예를 들어 setTimeout (anyFunction, 1000/fps)은 fps == 3 일 때 anyFunction을 초당 약 3 회 트리거합니다.RAF + setTimeout에 대한이 기사를 참조하십시오. http://creativejs.com/resources/requestanimationframe/

setTimeout이없는 RAF는 여전히 작동하지만 RAF는 fps 간격보다는 가능한 빨리 머리카락을 키우려고합니다.

+0

var hair = new 머리카락 (25,50,150,50,8); 이제는 이것이 당신이 만든 인스턴스라고 생각합니다. 그러나 무엇을 참조하는지 혼란 스럽습니다. 머리카락은 외부 객체이고 함수 이름은 이고 direction = 0.25의 용도는 무엇입니까? –

+0

그리고 whats 콜백 함수의 의미와 그 settimeout? 나는 코드를 주석 처리하고 실행했다. 여전히 크롬 브라우저에서 잘 돌아가고 있었다. –

+1

질문에 대한 추가 답변을 참조하십시오. :) – markE

관련 문제