는 머리를 성장에 대해 원하는 답변입니다.
머리카락을 "개체"로 만드는 방법에 대한 정보도 있습니다.
코드와 바이올린 : 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 간격보다는 가능한 빨리 머리카락을 키우려고합니다.
나는 코드를 가져 와서 생성자가있는 Hair "클래스"버전을 만들었습니다. 이 클래스에 필요한 털의 수를 입력하고 필요에 따라 모든 털을 그룹으로 그리거나 다시 그립니다. mousemove 핸들러는 9 개의 개별 객체 대신 하나의 그룹에만 응답해야하기 때문에 성능 향상을 위해이 작업을 수행했습니다. 나는 또한 머리카락을 자라게하는 클래스의 메서드를 추가했습니다. 앞서 설명한 것처럼 제어점과 끝점의 "Y"좌표를 높이면됩니다. 프로젝트에 행운을 빈다. :) – markE
@markE : 내가 성장한 머리카락을 넘을 순간, 그들은 짧아 져서 바람직하지 않다 ...하지만 괜찮아 ... 나는 여기에서 계속 될 것이다. 감사 마크 !!! 심각하지만 ... 작다. 질문과는 별도로, 56 세의 나이에 당신을 계속 지킵니다 !!! # 존경 –
나는 매일 새로운 것을 배울 때 가장 행복합니다. 지금까지 인생은 배우기에 충분한 재미있는 것들을 제공했습니다! – markE