tags:

views:

155

answers:

2

The following code won't load the green rectangle in the canvas. This is my very first time trying out jquery (either it sucks or me sucks), why such a simple thing is not working, I'm buffled. browser = ff3.6. thanks Playing with jquery because there's another jquery driven piece of code that could be quite useful...

<html>
<head>
<style type="text/css">
 #canvas {
 border:1px solid black;
 }
</style>

<script type="text/javascript" src="/js/jquery-1.4.2.min.js"/>
<script type="text/javascript">
// have also tried
<script type="application/javascript">

  $(function() {
 var canvas = $("#canvas")[0];
 var ctx = canvas.getContext("2d");

 // ctx.clearRect(0,0,300,300);
 ctx.fillStyle = "green";
 ctx.fillRect(0,0,50,50);

 });

</script> 
</head>

<body>
<canvas id="canvas" width="300" height="300">
</body>
</html>

A: 

Try this:

<script type="application/javascript">
    $(document).ready(function() {
        var canvas = $("#canvas")[0];
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            // Choose a color
            ctx.fillStyle = color;
            ctx.strokeStyle = color;
            ctx.fillRect(0, 0, 50, 50);
        } else {
            // Browser doesn't support CANVAS
        }
    });
</script>

That should work as expected. I suspect you were missing the $(document).ready() bit.

Nick Presta
No. still blank canvas. I added alert('poblem'); to the else blockIs my copy of FF hacked or my computer hacked?
Don Don
How to test if jquery is actually functioning correctly? tks.
Don Don
It works with Chrome 5.0. But jquery is so freaking picky?The following code won't work with firebug lite on chrome thouit complained about undefined$(document).keydown(function(e) { // console.log(e.keycode); alert(e.keycode);})
Don Don
A: 

Don Don,

You need to make two small changes.

First remove the [0] from this line,

var canvas = $("#canvas")[0]

Second, take that [0] and add it to the if statement,

if (canvas[0].getContext) {

And add it to the assignment of ctx

var ctx = canvas[0].getContext("2d");

Alternatively assign it to a variable before you test for it.

var canvas = $("#canvas"), ctx = canvas[0].getContext("2d");
if (ctx) {

And you should be good to go...

Adam Wiggall