我有一个fillRect,我每次更新输入值时都会尝试垂直移动。我的问题是,由于一些奇怪的原因,一旦输入值达到10,y边距就会跳跃。那是为什么?
document.addEventListener('DOMContentLoaded', domloaded, false);
function domloaded() {
//variables for canvas API
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
function draw() {
//GET current Yposition
var yPos = document.getElementById('yPos').value;
var y = 1 + yPos;
//remove previous canvas, necessary to reiterate
ctx.clearRect(0, 0, 700, 700);
//drawing
ctx.fillStyle = '#000';
ctx.fillRect(200, y, 200, 55);
requestAnimationFrame(draw);
}
draw();
}
body {
background-color: blue;
width: 100%;
height: 100%;
}
input,
h1 {
text-align: center;
font-size: 20px;
color: yellow;
box-sizing: border-box;
}
#container {
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
min-height: 500px;
}
.floatLeft {
float: left;
width: 50%;
padding: 5% 0;
background: red;
}
#control {
float: left;
width: 30%;
height: 500px;
background-color: red;
color: white;
}
#view {
float: left;
width: 70%;
height: 700px;
background-color: white;
color: white;
}
<body>
<div id="container">
<h1>Book Canvas Demo</h1>
<div id="control">
<h1 class="floatLeft">Y Position:</h1>
<input id="yPos" type="number" step="1" min="0" max="500" value="0" class="floatLeft">
</div>
<div id="view">
<canvas id="canvas" width="700" height="700"></canvas>
</div>
</div>
</body>
换句话说,如何正确添加值,使用requestAnimationFrame不断更新。谢谢。
答案 0 :(得分:2)
您正在尝试将yPos
用作数字,但实际上它是一个字符串。在我看来,将任何东西转换为数字的最简单方法是使用前面的一元加号:
var yPos = +document.getElementById('yPos').value;
document.addEventListener('DOMContentLoaded', domloaded, false);
function domloaded() {
//variables for canvas API
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
function draw() {
//GET current Yposition
var yPos = +document.getElementById('yPos').value;
var y = 1 + yPos;
//remove previous canvas, necessary to reiterate
ctx.clearRect(0, 0, 700, 700);
//drawing
ctx.fillStyle = '#000';
ctx.fillRect(200, y, 200, 55);
requestAnimationFrame(draw);
}
draw();
}
body {
background-color: blue;
width: 100%;
height: 100%;
}
input,
h1 {
text-align: center;
font-size: 20px;
color: yellow;
box-sizing: border-box;
}
#container {
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
min-height: 500px;
}
.floatLeft {
float: left;
width: 50%;
padding: 5% 0;
background: red;
}
#control {
float: left;
width: 30%;
height: 500px;
background-color: red;
color: white;
}
#view {
float: left;
width: 70%;
height: 700px;
background-color: white;
color: white;
}
<body>
<div id="container">
<h1>Book Canvas Demo</h1>
<div id="control">
<h1 class="floatLeft">Y Position:</h1>
<input id="yPos" type="number" step="1" min="0" max="500" value="0" class="floatLeft">
</div>
<div id="view">
<canvas id="canvas" width="700" height="700"></canvas>
</div>
</div>
</body>