如何在IF语句中调用使用canvas ex:function play(ctx){}的函数

时间:2016-01-15 14:05:30

标签: javascript html5-canvas

所以我想在if语句中调用一个函数。 :

window.onload = function()
{
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

function play(ctx)
{
ctx.fillStyle="white";
ctx.fillRect(490,80,100,30);
ctx.font = "16px Arial";
ctx.fillStyle="black";
ctx.fillText("Play",525,102);
}

 /////this is the part where of IF statement that I want to call the function

    if((X >= 380 && X <= 480) && (Y >= 100 && Y <= 180))
    {
     (function() { play(ctx); });  //this is where I want to put the code

     //play(ctx); when I call the function like this, an error appears

    } 


}

关于代码,当我使用由html5画布组成的框点击对象时,它应该调用播放(ctx)函数来制作播放按钮。问题是没有盒子出来。我试过用play(ctx);但是出现错误,它表示未捕获的TypeError:播放不是函数。请帮帮我。

感谢

1 个答案:

答案 0 :(得分:2)

声明onload函数的 ctx 播放 outsite:

&#13;
&#13;
window.onload = init;

var ctx = null;
var canvas = null;

function play(ctx) {
  ctx.fillStyle = "white";
  ctx.fillRect(490, 80, 100, 30);
  ctx.font = "16px Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Play", 525, 102);
}

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext('2d');

  if ((X >= 380 && X <= 480) && (Y >= 100 && Y <= 180)) {
    play(ctx);
  }
}
&#13;
&#13;
&#13;