如何设置样式到html5画布?

时间:2013-12-09 14:43:58

标签: javascript html5 canvas excanvas

我使用下面的代码将样式设置为“Canvas”。但我无法将"fillStyle"设置为画布。但是strokeStylelineWidth工作正常。

Init(){
     var can = byId('myCanvas');

        // get it's context
        hdc = can.getContext('2d');

        hdc.strokeStyle = 'red';
        hdc.lineWidth = 2;

        // Fill the path
        hdc.fillStyle = "#9ea7b8";
        hdc.fill();
}

//用坐标调用drawPoly函数。

function drawPoly(coOrdStr) {
        var canvas = byId('myCanvas');
        hdc.clearRect(0, 0, canvas.width, canvas.height);

        var mCoords = coOrdStr.split(',');
        var i, n;
        n = mCoords.length;
        hdc.beginPath();
        hdc.moveTo(mCoords[0], mCoords[1]);
        for (i = 2; i < n; i += 2) {
            hdc.lineTo(mCoords[i], mCoords[i + 1]);
        }
        hdc.lineTo(mCoords[0], mCoords[1]);
        hdc.stroke();

    }

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

您没有使用任何形状进行填充。你需要添加它。我猜你正在尝试填充整个画布。这对你有用。试试这个:

 var can=document.getElementById("myCanvas");
 var hdc=can.getContext("2d");
 hdc.strokeStyle = 'red';
 hdc.lineWidth = 2;
 hdc.fillStyle="#FF0000";
 hdc.fillRect(0,0,can.width,can.height);

<强> Working Fiddle