开发者

Why aren't these Canvases rendering?

I'm creating a web app that allows users to enter a number of colors, by specifying RGB values. Upon submission, the user will see a canvas with a solid rectangle drawn in the color chosen.

On this page, I have 7 canvases. The first one draws just fine, but none of the rest show up. The browser is Safari. Here's the relevant code:

First, the script element in the header, which defines the function I use to draw to the canvas.

<script language="JavaScript" TYPE="text/javascript"><!--
function drawCanvas(canvasId, red, green, blue) {
var theCanvas = document.getElementById("canvas" + canvasId);

     var context = theCanvas.getContext("2d");

     context.clearRect(0,0,100,100);
     context.setFillColor(red,green,blue,1.0);
     context.fillRect(0,0,100,100);
    }
    // -->
    </script>

Next, the HTML source, where I have my canvas tags and some embedded Javascript to call my drawCanvas function

<canvas id="canvas0" width="100" height="100">
  </canvas>


   <script language="JavaScript" TYPE="text/javascript"><!--
 drawCanvas(0,250,0,0);
   // -->
 </script>
.
. //more source
.
<canvas id="canvas1" width="100" height="100">
  </canvas>


   <script language="JavaScript" TYPE="text/javascript"><!--
 drawCanvas(1,4,250,6);
   // -->
 </script>

Also provided is a screenshot. As you can see, the "red" canvas c开发者_如何学JAVAomes up just fine, but the second one, which should be green, doesn't show up at all. Any ideas?

Why aren't these Canvases rendering?


There is some strangeness with the way setFillColor is interpreting the color values -- change the second call to drawCanvas(1,0,250,0) (instead of 4, 250, 6 for the last three args) and the green canvas shows just fine (on showing a local HTML file -- @Chetan's suggestion is worthwhile for pages that don't load that fast, but it doesn't solve your problem;-). This occurs in both Safari and Chrome. Unfortunately I cannot find a documentation for setFillColor (the coming HTML5 standard uses a different approach and does not appear to define such a method) so I can't check whether that's a webkit bug (webkit being what both Safari and Chrome are using for rendering) or a difference in what args setFillColor wants!

Edit: I experimented a bit and it seems it wants the RGB component in the range 0.0 to 1.0, not 0 to 255. Changing the call to setFillColor to:

 context.setFillColor(red/256,green/256,blue/256,1.0);

therefore appears to work just fine.


You need to wait until the page has loaded until you can reliably do document.getElementById. You'd usually do DOM manipulation in window onload or DOMContentLoaded event.

This should work:

window.onload = function() {
     drawCanvas(0,250,0,0);
     drawCanvas(1,4,250,6);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜