如何有条件地将不同背景应用于画布

时间:2015-07-09 11:40:22

标签: javascript html

此处显示的代码可能对其他人有用:它显示了我想出的解决方案,我必须有条件地将不同的背景图像应用到画布。之前已经提出了关于如何实现这一点或其变体的问题。

(抱歉我的编辑很糟糕。我最初发布这是一个问题,然后,在阅读我发布的代码时,答案就明白了,所以我删除了帖子的那一部分。我没有意识到已经有两个答案的时间对于那些没有看到原始问题的人来说是没有意义的。所以,总结一下:我无法解决为什么我已经添加到其他人的功能&# 39;我正在调整的已发布代码无法被我的函数调用访问。我没有意识到我插入它们的代码是"包裹"在匿名IFFE函数内当我将它们移动到"包装器的末端以下时,我能够从IFFE外面调用它们。)

感谢javinor,链接到解释IFFE功能的非常翔实的文章。

至于下面显示的方法,我发现了一种更好的方法。我了解到div元素并不属于HTML头部分,因此这是一种更好的方法:

<head>
<div id="conditionalCSSincludes">

  <!--
    The javascript below will insert an inner div section here called "CanvasStyles", which
    will, conditionally, contain one of the following two lines. That line will link to one of
    two external style sheets containing the canvas style for the canvas displayed by this page.

    <link rel="stylesheet" type="text/css" href="CanvasStylesA.css">
    <link rel="stylesheet" type="text/css" href="CanvasStylesB.css">

    The two style sheets differ with respect to the background image set for Canvas1.
    A sets it to A.jpg, B sets it to B.jpg.
  -->

</div>
<script src="code.js" type="text/javascript"></script>
<!-- the javascript below goes here -->
</head>

<body>
 <canvas width="530" height="530" id="Canvas1">
 <p>This page will not display correctly because your browser does not support the canvas element. Sorry.</p>
 </canvas>
</body>

您可以围绕决定使用哪个文件的href行包装条件。

HTML

<script type="text/javascript">
  var includesDiv1, includesDiv2, includesDiv3, dt, hour, Bgnd;

  // Conditional code that, depending on page load time, chooses
  // whether to display the night-time or daytime background

  dt = new Date();
  hour = dt.getHours();

  // for testing, enable the line below and set the hour manually ...
  // hour = 6;

  if (hour < 6 || hour >= 18){Bgnd = 1;} else{Bgnd = 2;}

  // These are the two versions of the include link to the external style sheets:
  includesDiv1 = '<div id="CanvasStyles"> <link rel="stylesheet" type="text/css" href="CanvasStylesA.css"> </div>';
  includesDiv2 = '<div id="CanvasStyles"> <link rel="stylesheet" type="text/css" href="CanvasStylesB.css"> </div>';

  if (Bgnd==1){
     includesDiv3 = includesDiv1;  // use the night-time background image
  }
  else{
     includesDiv3 = includesDiv2;  // use the daytime background image
  }

  // Insert into the conditionalCSSincludes div above an inner div called "canvasStyles".
  // It contains an html include link to an external css file containg canvas styles.

  cssIncludesDiv = document.getElementById("conditionalCSSincludes");
  cssIncludesDiv.innerHTML = includesDiv3;

的Javascript

{{1}}

2 个答案:

答案 0 :(得分:0)

正好在

之下
window.startClock = startClock;
window.stopClock = stopClock;

添加

window.yourFunctionName = yourFunctionName

为您的三个函数执行此操作,以便它们可在全局(窗口)范围中使用

答案 1 :(得分:0)

@pawel点击该按钮,无法在IIFE范围之外访问IIFE (function () {}())中定义的所有内容。

查看this关于模块和命名空间的非常有启发性的解释。