Javascript - HTML5输入范围滑块 - 动画速度

时间:2016-12-26 21:35:11

标签: javascript html5 html5-canvas

我正在尝试使用HTML 5滑块。我试图让它改变变量moveX的值。第52行可以工作,但这是静态的。第53和54行是我尝试过的,但它只会产生不稳定的运动。有人可以帮助我吗?

以下是该页面的链接:http://hyque.com/ani/drawImageBtnFwd.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>DrawImage with Buttons</title>
</head>

<body>

<button id="startBtn">Start</button>
<button id="stopBtn">Pause</button><br />
<p>
<strong>Speed</strong>
<input id="slider1" type="range" min="1" max="10" value="0" step="1">

</p>

<canvas id="myCanvas" width="1200" height="187" style="border:1px solid #d3d3d3;">

<script>


window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = "http://hyque.com/ani/adam.png";  
var xPos = 0;
var moveX = 0;
var scaleSlider = document.getElementById("slider1");

ctx.drawImage(img, 0, 0, 120, 182, 0, 0, 120, 182);


//number(scaleSlider);
var el = document.getElementById('startBtn');
el.addEventListener('click', strt, false);

var el2 = document.getElementById('stopBtn');
el2.addEventListener('click', stopIt, false);

function imageXPosition() {


ctx.clearRect(0, 0, 1200, 182);  // This clears the canvas

ctx.drawImage(img, xPos, 0, 120, 182, moveX, 0, 120, 182); //Draws the    individual frames


xPos += 120; //adds the width

//moveX += 5;
moveX += scaleSlider.value;
//scaleSlider.onchange = function(e){moveX = e.target.value;}


//This adds 1 to the second frame
if(xPos == 120){
    xPos += 1;
} 
if(xPos > 841){xPos = 0;}   // This resets to 0 after the las frame
if(moveX >= 1200){moveX = 0;}

}
 var intStp; // declared outside the strt() function, because 

function strt(){
clearInterval(intStp); //without this lin the animation will speed up   eachtime you click "Start Button"
intStp = setInterval(imageXPosition, 200);

}
function stopIt(){
    clearInterval(intStp);
}   
 }

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

从我看到的这一行有问题: moveX + = scaleSlider.value;

scaleSlider.value返回一个字符串。 moveX也是一个字符串。

当上面的行被调用时,你有这样的东西

&#34; 0&#34; + =&#34; 1&#34;结果是&#34; 01&#34; 在它之后&#34; 01&#34; + =&#34; 2&#34;这导致&#34; 012&#34;等

在解决任何问题之前,请确保使用parseInt(moveX,10);

这将允许您继续。