我创建了一个这样的简单网站,当点击该框时,将球放入框中。但每次只有一个球落下。当盒子被多次点击时,我希望多个球落入盒子中:
以下是我使用的代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function popup (n) {
var context;
var dx= 4;
var dy=4;
var y=25;
var elWidth=150;
var ballWidth=10;
var x=(elWidth+ballWidth)/2;
var counter = 0;
var myCanvas=document.getElementById('myCanvas'+n);
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,200,235);
context.beginPath();
context.fillStyle="red";
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
if(y>300){clearInterval(interval);}
if( y<0 || y>224)dy=0;
y+=dy;
myCanvas.className='active';
}
var interval=setInterval(draw,10);
}
</script>
<style>
html,body{
margin:0;
}
div.time {
display: table;
background: green;
float: left;
margin: 20px;
zoom: 1;
position: relative;
top: 75px;
left:35px;
width: 150px;
height: 150px;
}
span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
canvas{
z-index:10000;
transform: inherit;
float: left;
margin: 20px;
zoom: 1;
position: relative;
top: -200px;
left:35px;
margin:20px;
}
#myCanvas1{clear:left;}
</style>
</head>
<body>
<div class="time"><span>Past Thoughts</span></div>
<div class="time"><span>Present Thoughts</span></div>
<div class="time"><span>Future Thoughts</span></div>
<canvas id="myCanvas1" width="150" height="235" onclick="popup(1)"></canvas>
<canvas id="myCanvas2" width="150" height="235" onclick="popup(2)"></canvas>
<canvas id="myCanvas3" width="150" height="235" onclick="popup(3)"></canvas>
</body>
</html>
我希望多次点击框时应将多个球放入盒子中。但是老球应该留在盒子里。如何实现?我想添加一些响应,以便它可以在手机和平板电脑上进行测试。如何在不改变功能的情况下完成?
答案 0 :(得分:1)
更改脚本如下。
var myCanvas, context;
var balllist = [];
var counter = 0;
var interval;
window.popup = function (n) {
var dy = 4, y = 25;
var elWidth = 150;
var ballWidth = 10;
var x= (elWidth + ballWidth) / 2;
counter++;
// create a new ball
balllist.push({x: x, y: y, dy: dy});
myCanvas = document.getElementById('myCanvas' + n);
context = myCanvas.getContext('2d');
function draw() {
context.clearRect(0,0,200,235);
for (var i = 0; i < balllist.length; i++) {
var ball = balllist[i];
context.beginPath();
context.fillStyle="red";
context.arc(ball.x, ball.y, 10, 0, Math.PI*2, true);
context.closePath();
context.fill();
if (i == balllist.length - 1 && ball.y > 300) {
clearInterval(interval);
}
if(ball.y < 0 || ball.y > 224) ball.dy = 0;
ball.y += ball.dy;
}
}
clearInterval(interval);
interval = setInterval(draw, 10);
}
此代码仅适用于一个画布。创建另一个balllists(如canvas2的balllist2)并修改弹出功能以使用该balllist。