我正在尝试了解如何在特定元素中添加基本交互性。在这里,我希望用户能够按任何箭头键,并看到元素旋转并相应地翻译。我不确定为此使用DOM VS画布之间的区别,但是我知道如何与我在此处选择的DOM一起使用。我的问题是元素在动作中不一致,我认为这是因为我意外地用我的功能覆盖了变换值。
这是下面的摘要。除了down
键外,所有箭头键都在执行任何操作。
function rotate( e, n ) { //get current rotation and add n to it
var curTranslation = getTrans( e );
e.style.transform =
'rotate( ' + n + 'deg ) translateY(' + curTranslation + 'px )';
}
function translate( e, n ) { //get current translation and add n to it
var curRotation = getRot( e );
e.style.transform =
'rotate( ' + curRotation + 'deg ) translateY(' + n + 'px )';
}
function checkKey( e ) { //fire when a key on the keyboard is pressed.
var d = document,
triBx = d.getElementById( 'tri-bx' );
if ( e.keyCode == '38' ) { //up
countTrans = Math.abs( countTrans ) * -1.1;
translate( triBx, countTrans );
}
else if ( e.keyCode == '40' ) { //down
body.innerHTML = 'down';
}
else if ( e.keyCode == '37' ) { //left
countRot = Math.abs( countRot ) * -1.1;
rotate( triBx, countRot );
}
else if ( e.keyCode == '39' ) { //right
countRot = Math.abs( countRot ) * 1.1;
rotate( triBx, countRot );
}
}
function start() { //call first function
var d = document,
triBx = d.getElementById( 'tri-bx' );
window.addEventListener( 'keydown', checkKey );
}
//prevent entire window from scrolling
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
start();
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
.tri-bx {
transform: rotate( 0 );
transition: transform 1s;
}
.tri {
width: 0;
height: 0;
border-left: 1rem solid transparent;
border-right: 1rem solid transparent;
border-bottom: 1rem solid black;
transform: scaleX( 0.5 );
}
<div id="tri-bx" class="tri-bx">
<div id="tri" class="tri"></div>
</div>
<p style="position:absolute; bottom: 0;">use arrow keys</p>
<script>
var countRot = 1, //keep track of how many times the keys are pressed for rotation
countTrans = 1; //Same for translation
function getRot( e ) { //get rotation angle of element
var st = window.getComputedStyle( e, null ),
tr = st.getPropertyValue( 'transform' ) || 'FAIL',
values = tr.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' ),
a = values[ 0 ],
b = values[ 1 ],
c = values[ 2 ],
d = values[ 3 ],
scale = Math.sqrt( a * a + b * b ),
sin = b / scale,
angle = Math.round( Math.atan2( b, a ) * ( 180 / Math.PI ) );
return angle;
}
function getTrans( e ) { //get translation value of element
var st = window.getComputedStyle( e, null ),
tr = st.getPropertyValue( 'transform' ) || 'FAIL',
values = tr.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' ),
f = values[ 5 ];
return f;
}
</script>
我的问题是为什么对象在屏幕上跳过,以及如何避免覆盖转换以使其正常工作。想法?
您使用的是不打算做的转换。该元素始终从其原始位置转换。这就是为什么将其翻译然后更改旋转后,它会旋转一束(这可能不是您期望发生的情况(。如果您考虑一下,它会以程度旋转,因此,您将三角形从"中间"或从中启动的位置移动到越远的距离,它将移动的距离就越多。
我建议您要么使用帆布(有一些很棒的游戏库,使其比您想象的要容易(。请记住,CSS是用于样式而不是交互的创建的。