javascript – document.getElementById().getContext(‘2d’)不是函数

前端之家收集整理的这篇文章主要介绍了javascript – document.getElementById().getContext(‘2d’)不是函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这不断得到一条错误消息,说它不是一个功能,请帮助!!
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,100,100);
    }
    image();

</script>

我已经四处寻找,但是我没有找到任何有效的东西;我不知道它是否必须对我的jquery做任何事情.

解决方法

你在那里引用了那个id的div …
DIV没有像.getContext()这样的属性方法,所以这里是工作部分:
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,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>
原文链接:https://www.f2er.com/js/240704.html

猜你在找的JavaScript相关文章