2010-12-22 94 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