HTML:
<div id="container">
<canvas id="canvas" width="1024" height="1024"></canvas>
</div>
<button id = "click" >fire</button>
<script type="text/javascript" src = "Jquery/easy.js"></script>
的javascript:
var ctx = canvas.getContext('2d');
var chop1 = new Image();
chop1.src = "img/chopper.png";
var blt = new Image();
blt.src = "img/bullet.png"
var chopperX = 0;
var chopperY = 0;
var ascent = 2;
var limit = 500;
var start = null;
var bltX = 135;
var hit = document.getElementById("click");
window.onclick = function()
{
fly()
}
hit.onclick = function()
{
fire();
}
function fire()
{
bltX +=ascent;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(blt,bltX,30,
chop1.width, chop1.height);
requestAnimationFrame(fire);
}
function up()
{
chopperY-=ascent;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(chop1,0,chopperY ,
chop1.width, chop1.height);
requestAnimationFrame(up);
if(chopperY == 0){
fly();
}
}
function fly() {
chopperY+=ascent;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(chop1,0,chopperY ,
chop1.width, chop1.height);
if (chopperY < limit) {
requestAnimationFrame(fly);
}
if(chopperY==limit){
up();
}
}
当我点击开火按钮时,它不会调用“火”方法并调用“飞行”功能。我想知道为什么“飞”方法被调用而不是“火”方法? 这段代码有什么错误吗?它的解决方案是什么?
答案 0 :(得分:1)
您有两个事件处理程序
window.onclick = function() {
fly()
}
hit.onclick = function() {
fire();
}
顺便写一下
window.onclick = fly;
等。但是,当您点击window
内的任何元素,即window
时,点击气泡到hit
级别,因此也会调用fly()
函数。
您可以尝试停止传播
hit.onclick = function(event) {
event.stopPropagation();
fire();
}
答案 1 :(得分:0)