2010-12-22 81 views
0

我想在画布上绘制简单的矩形。这是我的代码。代码完全执行。但它完全只画出7个矩形,而8个半画。 最后两个矩形未绘制。我究竟做错了什么?我尝试过IE9测试版,FF3和Chrome 9.请帮忙。不能在画布上绘制八个以上的矩形

<html> 
<head> 
<script src="javascript/jquery-1.4.4.min.js"></script> 
<script type="text/javascript" language="javascript"> 

$(document).ready(function() { 
    drawsegment($('#divTree')); 
}); 

function drawsegment(widget) { 
    var $ctx = $('<canvas />', { 
     width: '300', 
     height: '200' 
    }); 
    widget.html($ctx); 
    var ctx = $ctx[0].getContext('2d'); 

    ctx.fillStyle = "red"; 
    ctx.fillRect(0, 0, 255, 20); 
    ctx.fillStyle = "yellow"; 
    ctx.fillRect(0, 20, 255, 20); 
    ctx.fillStyle = "blue"; 
    ctx.fillRect(0, 40, 255, 20); 
    ctx.fillStyle = "green"; 
    ctx.fillRect(0, 60, 255, 20); 
    ctx.fillStyle = "violet"; 
    ctx.fillRect(0, 80, 255, 20); 
    ctx.fillStyle = "white"; 
    ctx.fillRect(0, 100, 255, 20); 
    ctx.fillStyle = "black"; 
    ctx.fillRect(0, 120, 255, 20); 
    ctx.fillStyle = "gray"; 
    ctx.fillRect(0, 140, 255, 20); 
    ctx.fillStyle = "yellow"; 
    ctx.fillRect(0, 160, 255, 20); 
    ctx.fillStyle = "blue"; 
    ctx.fillRect(0, 180, 255, 20); 
} 

</script> 
</head> 
<body> 
    <div id="divTree"></div> 
</body> 
</html> 
+0

喜阿维纳什,它的工作原理,如果帆布在标记中定义。但在我的代码中动态创建画布时不起作用。 – harsha 2010-12-22 09:31:23

回答

1

画布的宽度和高度应定义画布元件本身,而不是风格属性的属性:

var $ctx = $('<canvas />'); 
widget.html($ctx); 
widget.children('canvas').attr('width',300).attr('height',200); 
+0

谢谢安德烈,它的工作原理与预期完全一样。 – harsha 2010-12-22 15:07:01