设置HTML5 Canvas的背景填充,描边和不透明度

Bha*_*thi 13 javascript jquery html5 canvas

我使用下面的代码来设置样式myCanvas,但我无法设置fillStyle.然而,strokeStyle并且lineWidth工作正常.有人可以帮忙吗?

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

    }
Run Code Online (Sandbox Code Playgroud)

Pro*_*eek 19

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';
}  
Run Code Online (Sandbox Code Playgroud)

小心,style.height否则style.width不适用于画布.


for*_*net 15

风格/ CSS:

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

jQuery的:

$('#myCanvas').css('background-color', 'rgba(158, 167, 184, 0.2)');
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

document.getElementById("myCanvas").style.backgroundColor = 'rgba(158, 167, 184, 0.2)';
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用jQuery添加CSS? (8认同)