【问题标题】:Can't draw more than eight rectangles on a canvas不能在画布上绘制超过八个矩形
【发布时间】:2010-12-22 19:34:18
【问题描述】:

我正在尝试在画布上绘制简单的矩形。这是我的代码。 代码完全执行。但它只完全绘制了 7 个矩形和第 8 个一半。 最后两个矩形未绘制。我究竟做错了什么?我在 IE9 beta、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>

【问题讨论】:

  • 嗨,Avinash,如果在标记中定义了画布,它就可以工作。但在我的代码中动态创建画布时不起作用。

标签: html canvas


【解决方案1】:

画布的宽度和高度应该是画布元素本身的定义属性,而不是样式属性:

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

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2013-01-24
    • 2015-03-16
    相关资源
    最近更新 更多