2014-02-23 1 views
0

x 속도와 y 속도의 두 입력을 사용하여 사용자가 결정한 속도로 캔을 바운스하게 만드는 프로그램을 만들고 있습니다. 그것은 공 문자열 위치에서 사용할 문자열을 정수로 변환하더라도 사용자 값을 undefined로 반환합니다. 나는 지난 며칠 동안이 작업을 해왔고, 해결하기가 정말 간단하다고 확신합니다. 어떤 도움이라도 대단히 감사하겠습니다.입력이 undefined로 반환되고 캔버스에서 x 및 y 위치로 작동하지 않습니다.

<script type="text/javascript"> 
    window.onload= function() 
     { 
      document.getElementById("changeButton").onclick = draw; 
     } 

    function draw(){ 
     //alert("Hey you made it!" + "\n" + "dx: " + dx + "\n" + "dy: " + dy); //alert which returns dx and dy for following stack commented out when not in use otherwise alert happens every 10 ms 

    //variables 
     var hVel = parseInt(document.getElementById("hVelocityBox").value, 10); //gets value for x movement and converts from string to int 
     var vVel = parseInt(document.getElementById("vVelocityBox").value, 10); //gets value for y movement and converts from string to int 
     var dx= hVel; 
     var dy= vVel; 
     var y=150; //default x position 
     var x=150; //default y posiiton 
     var context = myCanvas.getContext('2d'); 

    //refreshes the canvas 
     context.clearRect(0,0,300,300); 

    //draws circle 
     context.beginPath(); 
     context.fillStyle="#0000ff"; 
     context.arc(x,y,20,0,Math.PI*2,true); 
     context.closePath(); 
     context.fill(); 

    //code for movement 
     if(x<0 || x>300) //position limiter in x 
      dx=-dx; //reverses x movement 
     if(y<0 || y>300) //position limiter in y 
      dy=-dy; //reverses y movement 

     x+=dx; // 
     y+=dy; 
    }//close draw 
    setInterval(draw,10); //runs draw every 10 ms 
</script> 
<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>HTML5 Bouncing Ball</title> 
</head> 
<body> 
    <h1>Bouncing a Ball Around with HTML5 and JavaScript</h1> 
    <div id="container"> 
     <canvas id="myCanvas" width="300" height="300" style="border: 1px solid black"></canvas><br/> 

    <!--Textfields for x and y velocities, values defaulted to 4 --> 
     Horizontal Velocity <input id="hVelocityBox" type="text" value="4"/><br /> 
     Vertical Velocity <input id="vVelocityBox" type="text" value="4"/><br /> 

     <button id="changeButton">Change</button> 
    </div> 
</body> 
</html> 

답변

1

여기에 몇 가지 문제가 있습니다. 기본적으로 함수가 실행될 때마다 위치와 속도가 재설정됩니다. 나는 draw 함수 밖의 선언과 초기화를 옮겼다. 또한 단추에 바인딩 할 업데이트 함수를 추가했습니다. 그리기 기능을 방해하지 않고 업데이트 할 수 있습니다. 상자 안쪽에 볼을 유지하는 더 확실한 방법을 고려하고 싶을 수도 있습니다. http://jsfiddle.net/azurelogic/yz7LF/14/

document.getElementById("changeButton").onclick = update; 
var y=150; //default x position 
var x=150; //default y posiiton 
var dx = parseInt(document.getElementById("hVelocityBox").value, 10); //gets value for x movement and converts from string to int 
var dy = parseInt(document.getElementById("vVelocityBox").value, 10); //gets value for y movement and converts from string to int 

function update(){ 
    x = 150; 
    y = 150; 
    dx = parseInt(document.getElementById("hVelocityBox").value, 10); //gets value for x movement and converts from string to int 
    dy = parseInt(document.getElementById("vVelocityBox").value, 10); //gets value for y movement and converts from string to int 
} 

function draw(){ 
    var context = myCanvas.getContext('2d'); 

    //refreshes the canvas 
    context.clearRect(0,0,300,300); 

    //draws circle 
    context.beginPath(); 
    context.fillStyle="#0000ff"; 
    context.arc(x,y,20,0,Math.PI*2,true); 
    context.closePath(); 
    context.fill(); 

    //code for movement 
    if(x<0 || x>300) //position limiter in x 
    { 
     //these may help prevent accidental escapes 
     //if (x<0) x = 0; 
     //if (x>300) x = 300; 
     dx=-dx; //reverses x movement 
    } 
    if(y<0 || y>300) //position limiter in y 
    { 
     //these may help prevent accidental escapes 
     //if (y<0) y = 0; 
     //if (y>300) y = 300; 
     dy=-dy; //reverses y movement 
    } 
    x+=dx; 
    y+=dy; 
};//close draw 

setInterval(draw,10); //runs draw every 10 ms 
+0

+1 좋은 솔루션 :

는 여기가 제대로 작동와 바이올린입니다. 공이 반경을 따라 튀어 나오지 않도록'if (x <20 || x> 280)'및'if (y <20 || y> 280) '로 공의 반경을 조정할 수 있습니다. – markE

+0

나는 당신의 도움 덕분에 일하는 것을 끝내었다! 내가 HTML을 완전히로드 할 때까지 Js를 실행하기 위해 기다리지 않고 있다는 것을 깨닫지 못한 채로 끝내는 주요 문제. window.onload = function()을 사용하면 작동하지 않는 것 같아요. 그래서 제 수정이 JS 이전에 HTML을 코딩하는 결과를 낳았습니다. 이것은 괜찮은 수정인가요? 아니면 성숙한 수정입니까? – Mabbott

+0

캔버스 자체의 onload 이벤트에 연결하거나 jQuery를 가져 와서 document.ready를 사용할 수 있습니다. 또한 페이지 스피드 권장 사항과 같은 것을 보는 경우 필수적이지 않은 JS는 폴드 콘텐츠 아래에 있어야합니다. – azurelogic

관련 문제