HTML5 Canvas在外部JavaScript文件中无法使用 [英] HTML5 Canvas not working in external JavaScript file

查看:250
本文介绍了HTML5 Canvas在外部JavaScript文件中无法使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < p>我已经用JavaScript编写了这段代码,并且在我的index.html页面上可以正常工作。 ; canvas id =bannerCanvaswidth =960height =200> 
您的浏览器不支持canvas元素。
< / canvas>

< script type =text / javascript>

var canvas = document.getElementById(bannerCanvas);
var context = canvas.getContext(2d);
context.beginPath();
context.moveTo(25,25);
context.lineTo(355,55);
context.lineTo(355,125);
context.lineTo(25,125);
context.moveTo(465,25);
context.fill();
};
< / script>

...但是,当我将它放在一个外部的JavaScript文件中,它将无法正常工作!在索引页面的头部,我已经声明:

 < script type =text / javascriptsrc =的JavaScript / functionality.js> 
< / script>

我将此functions.js文件保存在JavaScript目录中,我尝试过执行其他JS函数在这个文件中检查索引页面和JS是否连接,他们是...答案可能是盯着我的脸,但由于某些原因我看不到它!



任何帮助都非常感激,谢谢。



编辑:我一直在使用Firebug,它给我没有错误,当我使用索引上的代码页面,当我使用外部JS文件时,我看到我想要的形状我只是看到一个大的黑色矩形。

解决方案

原因是脚本正在渲染canvas元素之前运行。



要修复它,请将其添加到外部文件中。

  document.addEventListener('DOMContentLoaded',domloaded,false); 
function domloaded(){
//你的代码在这里。
}

或与jquery

  $(function(){
//你的代码在这里
});


I have written this code in JavaScript and works perfectly fine when I include it on my index.html page:

<canvas id="bannerCanvas" width="960" height="200">
    Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">

   var canvas = document.getElementById("bannerCanvas");
   var context = canvas.getContext("2d");
     context.beginPath();
     context.moveTo(25,25);
     context.lineTo(355,55);
     context.lineTo(355,125);
     context.lineTo(25,125);
     context.moveTo(465,25);
     context.fill();
};  
</script>

...however when I place it in an external JavaScript file, it won't work! In the head of the index page, I have declared this:

 <script type="text/javascript" src="JavaScript/functionality.js">
 </script>

And I save this functionality.js file in the JavaScript directory, I've tried doing other JS functions in this file to check the index page and the JS are connected and they are...The answer is probably staring me in the face but for some reason I cannot see it!

Any help is much appreciated, thank you.

EDIT: I've been using Firebug and it is giving me no errors, when I use the code on the index page, I am seeing the shape I want yet when using the external JS file I am just seeing a big black rectangle.

解决方案

the reason for this is that the script is being run before the canvas element is rendered.

To fix it, add this in your external file.

document.addEventListener('DOMContentLoaded',domloaded,false);
function domloaded(){
    // your code here.
}

or with jquery

$(function(){
    // your code here.    
});

这篇关于HTML5 Canvas在外部JavaScript文件中无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆