Document.getElementById (). getContext ('2d') is not a function

This allows you to get an error message saying that this is not a function, please help!

var ctx = document.getElementById('canvas').getContext('2d');

HTML:

<html>
<head>
    <title>Canvas Race</title>
    <script src="jquery-2.2.3.js"></script>
     <style type="text/css">
        canvas {
            border: 1px solid black;
            background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
            background-size: 200px 300px;
            background-position-y: -81px;
        }
        </style>
</head>
<body>

    <div id="canvas">
        <canvas id="myCanvas" width="1100" height="150" ></canvas>
    </div>
    <div id="winner"></div>

</body>
</html>

JavaScript:

<script type="text/javascript">
    var blueCar = new Image();
    var redCar = new Image();

    // images
    function image(){
        blueCar.src = "http://worldartsme.com/images/car-top-view-clipart-1.jpg";
        redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";
        window.requestAnimationFrame(draw);
    }
    function draw() {
        var ctx = document.getElementById('canvas').getContext('2d');
        ctx.globalCompositeOperation = 'destination-over';

        //blue car
        ctx.drawImage(blueCar, 10, 10, 100, 100);
    }
    image();

</script>

I already searched, but I did not find anything that works, I do not know if he needs to do anything with my jquery.

+4
source share
1 answer

You referenced a div with this identifier ... DIVs do not have a property method such as .getContext () , so here is the working part:

    var blueCar = new Image();
    var redCar = new Image();

    // images
    function image(){
        blueCar.src = "http://worldartsme.com/images/car-top-view-clipart-1.jpg";
        redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";
        window.requestAnimationFrame(draw);
    }
    function draw() {
        var ctx = document.getElementById('canvas').getContext('2d');
        ctx.globalCompositeOperation = 'destination-over';

        //blue car
        ctx.drawImage(blueCar, 10, 10, 100, 100);
    }
    image();
<html>
<head>
    <title>Canvas Race</title>
    <script src="jquery-2.2.3.js"></script>
     <style type="text/css">
        canvas {
            border: 1px solid black;
            background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
            background-size: 200px 300px;
            background-position-y: -81px;
        }
        </style>
</head>
<body>

    <div id="mycanvas">
        <canvas id="canvas" width="1100" height="150" ></canvas>
    </div>
    <div id="winner"></div>

</body>
</html>
Run codeHide result
+5
source

All Articles