1

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>

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.