使用getElementsByTagName()时未定义

时间:2017-10-29 16:35:50

标签: javascript html canvas

我有两个文件:sim.jssimulator.htmlsimulator.html中,我在sim.js代码中加载了<head>,并在<canvas> <body>中创建了simulator.html代码 但是,当我使用document.getElementsByTagName("canvas")[0]时,它会返回undefined。

在我的simulator.html

<!doctype html>
<html lang="en" data-manifest="" data-framework="typescript">

<head>
    <meta charset="utf-8">
    <title>Traffic Simulator</title>
    <link rel="stylesheet" type="text/css" href="/sim/sim.css">    
    <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 class="vis">
            <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>

在我的sim.js

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/// <reference path="../libs/core/enums.d.ts"/>
var pxsim;
(function (pxsim) {
    var loops;
    (function (loops) {
        /**
         * Repeats the code forever in the background. On each iteration, allows other code to run.
         * @param body the code to repeat
         */
        //% help=functions/forever weight=55 blockGap=8
        //% blockId=device_forever block="forever" 
        function forever(body) {
            pxsim.thread.forever(body);
        }
        loops.forever = forever;
        /**
         * Pause for the specified time in milliseconds
         * @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000
         */
        //% help=functions/pause weight=54
        //% block="pause (ms) %pause" blockId=device_pause
        function pauseAsync(ms) {
            return Promise.delay(ms);
        }
        loops.pauseAsync = pauseAsync;
    })(loops = pxsim.loops || (pxsim.loops = {}));
})(pxsim || (pxsim = {}));
function logMsg(m) { console.log(m); }
var pxsim;
(function (pxsim) {
    var console;
    (function (console) {
        /**
         * Print out message
         */
        //% 
        function log(msg) {
            logMsg("CONSOLE: " + msg);
            // why doesn't that work?
            //board().writeSerial(msg + "\n")
        }
        console.log = log;
    })(console = pxsim.console || (pxsim.console = {}));
})(pxsim || (pxsim = {}));
var pxsim;
(function (pxsim) {
    var actions;
    (function (actions) {
        /**
         * Set location of the traffic light on the map
         * @param location
         */
        //% blockId=set_traffic_light block="set traffic light at %location"
        function setTLightLocation(location) {
            if (location == 0 /* A1 */) {
                pxsim.board().setTrafficLight();
            }
        }
        actions.setTLightLocation = setTLightLocation;
    })(actions = pxsim.actions || (pxsim.actions = {}));
})(pxsim || (pxsim = {}));
/// <reference path="../node_modules/pxt-core/typings/globals/bluebird/index.d.ts"/>
/// <reference path="../node_modules/pxt-core/built/pxtsim.d.ts"/>
//declaring variable from the js library
//declare let ctx: CanvasRenderingContext2D;
// declare let car_no: number;
// declare let w: number;
// declare let h: number;
// //declare let roads: any[];
// //declare let intersections_arr: any[];
// //declare let cars: any[];
// declare let drawIntersection: any;
// declare let requestAnimFrame: any;
// //declare let canvas: HTMLCanvasElement;
// //Test variables
// declare let testV:any;
// //
// declare function distance_check(c1:any, c2:any, axis: string): boolean;
// declare function check_inter(c:any, inter:any, axis:string): boolean;
// declare function gen_dir(c:any, inter:any): void;
// declare function init(): void;
// declare function drawscene(): void;
// declare function left_greenc(): void;
// declare function drive_cars(): any;
// declare function drawcar(): any;
// declare function intersections(): any;
// declare function drawroad(): any;
// declare function animloop(): any;
// //Test Functions
// declare function checkFile(): any;
// //
/**
 * Code
 */
var pxsim;
(function (pxsim) {
    /**
     * This function gets called each time the program restarts
     */
    pxsim.initCurrentRuntime = function () {
        pxsim.runtime.board = new Board();
    };
    /**
     * Gets the current 'board', eg. program state.
     */
    function board() {
        return pxsim.runtime.board;
    }
    pxsim.board = board;
    /**
     * Represents the entire state of the executing program.
     * Do not store state anywhere else!
     */
    var Board = (function (_super) {
        __extends(Board, _super);
        function Board() {
            _super.call(this);
            //this.element = <HTMLDivElement><any>document.getElementById('svgcanvas');
        }
        Board.prototype.initAsync = function (msg) {
            document.body.innerHTML = ''; // clear children
            // document.body.appendChild(this.element);
            return Promise.resolve();
        };
        Board.prototype.setTrafficLight = function () {
            // ctx.save()
            // ctx.fillStyle = 'green';
            // ctx.fillRect(10,10,50,50);
            // ctx.fill();
            // ctx.restore();
            // console.log("end1");
        };
        return Board;
    }(pxsim.BaseBoard));
    pxsim.Board = Board;
    var requestAnimFrame = (function () {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            // window.mozRequestAnimationFrame    || 
            // window.oRequestAnimationFrame      || 
            // window.msRequestAnimationFrame     ||  
            // window.mozRequestAnimationFrame    || 
            // window.oRequestAnimationFrame      || 
            // window.msRequestAnimationFrame     ||  
            function (callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
    var car_no = 10;
    var canvas = document.getElementsByTagName("canvas")[0];
    var ctx = canvas.getContext("2d");

变量canvas未定义

0 个答案:

没有答案