How to set styles to html5 canvas?

308 Views Asked by At

I use the below code to set styles to "Canvas". but i am not able to set "fillStyle" to canvas. but strokeStyle and lineWidth is working fine.

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();
}

//And call the drawPoly function with coordinates.

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();

    }

anyone could help on this?

1

There are 1 best solutions below

1
On

You have not used any shape for fill. You need to add that.I guess you are trying to fill whole canvas. This would work for you then.Try This:

 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