Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background fill, stroke, and opacity of HTML5 Canvas

I use the below code to set styles of myCanvas, but I am not able to set fillStyle. Yet, strokeStyle and lineWidth is working fine. Could anyone please help with this?

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.opacity = 0.2;
        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();

    }
like image 653
Bharathi Avatar asked Dec 10 '13 07:12

Bharathi


People also ask

How do you change opacity in canvas?

You can change the opacity of new drawings by setting the globalAlpha to a value between 0.00 (fully transparent) and 1.00 (fully opaque). The default globalAlpha is 1.00 (fully opaque). Existing drawings are not affected by globalAlpha .

How do you fill a canvas in HTML?

The fill() method in HTML canvas is used to fill the current drawing path. The default is black. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.


2 Answers

Init()
{
    var can = document.getElementById('myCanvas');
    h = parseInt(document.getElementById("myCanvas").getAttribute("height"));
    w=parseInt(document.getElementById("myCanvas").getAttribute("width"));

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

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

    // Fill the path
    hdc.fillStyle = "#9ea7b8";
    hdc.fillRect(0,0,w,h);
    can.style.opacity = '0.2';
}  

Be careful that style.height or style.width will not work with canvas.

like image 105
ProllyGeek Avatar answered Oct 05 '22 23:10

ProllyGeek


Style / CSS:

<style>#myCanvas { background-color: rgba(158, 167, 184, 0.2); }</style>

jQuery:

$('#myCanvas').css('background-color', 'rgba(158, 167, 184, 0.2)');

JavaScript:

document.getElementById("myCanvas").style.backgroundColor = 'rgba(158, 167, 184, 0.2)';
like image 38
forsvunnet Avatar answered Oct 06 '22 00:10

forsvunnet