【发布时间】:2021-02-03 22:28:12
【问题描述】:
我目前有一个飞翔的小鸟游戏的开头,css 生成了一个小红球。我想用从互联网上获取的 jpg 图像替换球,我也可以从 css 中设置样式和控制/动画,就像我对球所做的那样。
图片来源:“https://img1.pnghut.com/16/12/25/KjSdhUe19q/logo-app-store-smiley-smile-score.jpg”
我尝试了各种方法将其放入 CSS 和 HTML 中,但不完全理解它们是如何联系在一起的。
如果我在 html 中添加图像(如我所做的那样),我可以不使用 CSS 设置它的样式吗?
现在,我想:
- 在屏幕上渲染图像(就像我所做的那样)
- 将其设置为与红球相同的规格(例如 20 x 20 等,包括起始位置、定位等)
目前,CSS 中的 TOP POSITION 似乎有效(当应用于图像时)但宽度和高度无效。我不得不将图像的宽度和高度硬编码到HTML。
请提供有关最佳实践和解决方案的任何解释。
完整的当前代码在这里:
https://repl.it/@iamapersonthing/flappybirds
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>FlappyBird</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="game">
<div id="block"></div>
<div id="hole"></div>
<div id="character">
<img src="https://img1.pnghut.com/16/12/25/KjSdhUe19q/logo-app-store-smiley-smile-score.jpg">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
*{
padding:0;
margin:0;
}
#game{
width:400px;
height:500px;
border: 1px solid greenyellow;
margin:auto;
overflow:hidden;
}
#block{
width:50px;
height:500px;
background-color:greenyellow;
position: relative;
left:400px;
animation:block 2s infinite linear;
}
@keyframes block{
0%{left:400px}
100%{left:-50px}
}
#hole{
width:50px;
height:150px;
background-color:red;
position: relative;
left:400px;
top:-500px;
animation:block 2s infinite linear;
}
#character{
width:20px;
height:20px;
background-color:red;
position: absolute;
top:100px;
border-radius:50%;
}
JavaScript
var block = document.getElementById("block");
var hole = document.getElementById("hole");
hole.addEventListener('animationiteration',() => {
var random = -((Math.random()*300)+150);
hole.style.top=random +"px";
});
【问题讨论】:
标签: javascript html css image