【问题标题】:Javascript - HTML5 Input Range Slider - Animation SpeedJavascript - HTML5 输入范围滑块 - 动画速度
【发布时间】:2016-12-27 07:09:33
【问题描述】:

我正在尝试让 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>

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    从我看来,这条线是有问题的: moveX += scaleSlider.value;

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

    当上面的行被调用时,你会遇到这样的事情

    "0" += "1" 这个结果是 "01" 在它之后是 "01" += "2" 导致 "012" 等等。

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

    这将允许您继续。

    【讨论】:

    • 好的,谢谢。我会努力解决的。但是我声明 moveX 是一个数字,所以问题一定出在 scaleSlider 中,因为使用“moveX =+ 5;”有效,只有当我添加滑块时。
    • 它适用于:moveX += parseInt(scaleSlider.value)
    • 那是我的意图,你解析两个
    • 非常感谢
    猜你喜欢
    • 2014-12-26
    • 2021-08-22
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多