user2673680
user2673680

Reputation: 11

Trouble using HTML5 canvas

I'm new to HTML5. I wonder why the following code can't show a rectangle on the screen?

<!DOCTYPE HTML>
<html>
<head>
    <title>WebServer Test</title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var userviewcanvas = $("userViewerCanvas");
            var userviewcontext = userviewcanvas.getContext("2d");
            userviewcontext.fillRect(40, 40, 100, 100);
        });
    </script>
</head>
<body>

    <canvas id="userViewerCanvas" width="200" height="300">this is canvas</canvas>
    <div><span id="message"> </span> </div>
    <div><span id="stream"></span></div>

</body>
</html>

Upvotes: 1

Views: 74

Answers (3)

VahidNaderi
VahidNaderi

Reputation: 2488

You missed the sharp sign in your jQuery selector expression and of course you need get(0) to get the plain javascript object instead of jQuery object:

var userviewcanvas = $("#userViewerCanvas").get(0);

Upvotes: 2

Conrad Lotz
Conrad Lotz

Reputation: 8828

There are a couple of ways you can try and solve this problem:

Normal jQuery

var userviewcanvas = $("#userViewerCanvas").get(0);

Normal Javascript

var userviewcanvas = document.getElementById("userViewerCanvas");

There is a plugin that you can also make use of:

jCanvas

Upvotes: 2

Vipul Vaghasiya
Vipul Vaghasiya

Reputation: 479

check this

<!doctype html>
<html>
<head>

<meta charset="utf-8">
<title>WebServer Test</title>


<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var userviewcanvas = $("#userViewerCanvas").get(0),
        userviewcontext = userviewcanvas.getContext("2d");
        userviewcontext.fillRect(40, 40, 100, 100);
    });
</script>
</head>

<body>

    <canvas id="userViewerCanvas" width="200" height="300">this is canvas</canvas>
    <div><span id="message"> </span> </div>
    <div><span id="stream"></span></div>

</body>
</html>

Upvotes: 3

Related Questions