Bra*_*ird 7 html javascript jquery canvas
我已经尝试了一切来解决这个问题,但没有任何效果。在这里发帖是我最后的手段。
我正在尝试编写一个简单的画布元素并动态加载所有内容,但没有任何效果。我在 game.js:33 上的 Google 控制台中不断收到错误“Uncaught ReferenceError: ctx is not defined”。
我最初认为这是因为 common.js 是在其他 2 个 javascript 文件之后加载的,所以我制作了一个加载器文件,它按照我想要的顺序加载每个 JS 文件。我使用 $.getScript() 和 $.when() 函数做到了这一点。不幸的是,这不起作用。所以 ctx var 正在加载,但由于某种原因它给了我错误。
我已经包含了下面的文件。在此先感谢您的帮助。
编辑:我只是尝试从每个单独的 JS 文件中取出所有代码,并按照它们的顺序将它们放在同一个文件中,现在它工作正常。但是很高兴知道为什么它根本不起作用。因为将我的所有代码都放在 1 个文件中会变得非常忙碌。谢谢你。
索引.php
<!doctype>
<html>
<head>
<title>Game - Unknown</title>
<link rel="stylesheet" href="./assets/css/default.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
<!--<script src="./assets/js/loader.js"></script>-->
<script src="./assets/js/common.js"></script>
<script src="./assets/js/graphics.js"></script>
<script src="./assets/js/game.js"></script>
</head>
<body>
<canvas id="viewport"></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
常见的.js
$(document).ready(function(){
// Setup the canvas game context for 2D
var canvas = document.getElementById("viewport");
var ctx = canvas.getContext("2d");
// Update the canvas dimensions to match window size when changed
$(window).resize(function(){canvasResize()}); canvasResize();
function canvasResize(){
var cWidth = window.innerWidth;
var cHeight = window.innerHeight;
canvas.width = cWidth;
canvas.height = cHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, cWidth, cHeight);
}
// Get center of things - Useful for centering images on canvas
function getCenter(dim){ return dim / 2 }
});
Run Code Online (Sandbox Code Playgroud)
图形.js
$(document).ready(function(){
function gfxTile(x, y, w, h, r, g, b, a)
{
ctx.fillStyle = "rgb(60, 60, 100)";
ctx.beginPath();
//ctx.moveTo(x + h / 2, y + w / 2);
ctx.moveTo(10, 10);
ctx.lineTo(105, 25);
ctx.lineTo(25, 105);
ctx.lineTo(25, 105);
ctx.closePath();
ctx.fill();
}
});
Run Code Online (Sandbox Code Playgroud)
游戏.js
$(document).ready(function(){
// START TEMPORARY
var mapSizeX = 10;
var mapSizeY = 10;
var mapArray = new Array();
function createMap()
{
for(x = 0; x < mapSizeX; x++)
{
mapArray[x] = [];
for(y = 0; y < mapSizeY; y++)
{
mapArray[x][y] = 0;
}
}
}
// END TEMPORARY
setInterval(mainLoop, 50);
function mainLoop()
{
//gfxTile(10, 10, 40, 40, 50, 50, 50, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
Run Code Online (Sandbox Code Playgroud)
var ctx = canvas.getContext("2d");ctx创建了一个在您传入的函数范围内调用的变量$(document).ready();
ctx当 game.js 内部的函数执行时,其作用域或父作用域中没有变量,window变量。
一个简单的解决办法就是改变
var ctx = canvas.getContext("2d");
Run Code Online (Sandbox Code Playgroud)
到
window.ctx = canvas.getContext("2d");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18020 次 |
| 最近记录: |