我正在使用Typescript中的一个项目。此问题涉及三个主要文件:simulator.ts
,sim.js
,simulator.html
。
从sim.js
simulator.ts
文件
在simulator.html
中,我已在sim.js
<head>
但是,当我尝试使用document.getElementsByTagName("canvas")[0];
并将其分配给变量时,变量未定义。
在我的simulator.html
:
<!doctype html>
<html lang="en" data-manifest="" data-framework="typescript">
<head>
<meta charset="utf-8">
<title>Traffic Simulator</title>
<style>
body {
background: transparent;
overflow: hidden;
}
</style>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<!-- preload index.js
<script>
$(document).ready(function(){
$("script").attr('src','TrafficSimulation/js/index.js')
});
</script> -->
<script src="/cdn/bluebird.min.js"></script>
<script src="/cdn/pxtsim.js"></script>
<script src="/sim/sim.js"></script>
<link rel="stylesheet" href="TrafficSimulation/css/style.css">
</head>
<body>
<div id="svgcanvas" style="height: 270;">
<canvas>
<div></div>
</canvas>
<div class="box">
Number of Cars:<br>
<br><input type="range" max="100" min="10" value="36" onChange="init();">
<span class="car_no">10</span>
</div>
<script></script>
</div>
</body>
在我的simulator.ts
中,我在命名空间中全局定义了以下变量
/// <reference path="../node_modules/pxt-core/typings/globals/bluebird/index.d.ts"/>
/// <reference path="../node_modules/pxt-core/built/pxtsim.d.ts"/>
namespace pxsim {
/**
* This function gets called each time the program restarts
*/
initCurrentRuntime = () => {
runtime.board = new Board();
};
/**
* Gets the current 'board', eg. program state.
*/
export function board() : Board {
return runtime.board as Board;
}
/**
* Represents the entire state of the executing program.
* Do not store state anywhere else!
*/
export class Board extends pxsim.BaseBoard {
public element : HTMLDivElement;
constructor() {
super();
this.element = <HTMLDivElement><any>document.getElementById('svgcanvas');
}
initAsync(msg: pxsim.SimulatorRunMessage): Promise<void> {
document.body.innerHTML = ''; // clear children
document.body.appendChild(this.element);
return Promise.resolve();
}
}
let requestAnimFrame: any = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback:any ){
window.setTimeout(callback, 1000 / 60);
};
})();
var car_no = 10;
console.log("canvas: "+document.getElementById("canvas1"));
var canvas: HTMLCanvasElement = document.getElementsByTagName("canvas")[0];
var ctx: CanvasRenderingContext2D = <CanvasRenderingContext2D>canvas.getContext("2d");