【问题标题】:Set background fill, stroke, and opacity of HTML5 Canvas设置 HTML5 Canvas 的背景填充、描边和不透明度
【发布时间】:2013-12-27 14:56:57
【问题描述】:

我使用下面的代码设置myCanvas的样式,但我无法设置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.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();

    }

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:
    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';
    }  
    

    注意style.heightstyle.width 不适用于画布。

    【讨论】:

      【解决方案2】:

      样式/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)';
      

      【讨论】:

      • 为什么要用jQuery来添加CSS?
      • 因为在使用画布时,能够使用代码更改外观通常是有好处的。不过你是对的,完全有可能用纯 CSS 做同样的事情。
      • 这是比fillRect更好的解决方案
      • 在任何情况下,这都不是比 fillRect 更好的解决方案。因为:如果您将此画布设置为 div 背景,如果您使用 画布(设置为 div 的背景)将有背景,如果您将使用 fillRect 代替。在其他情况下,jquery 的解决方案比 fillRect 短得多。
      【解决方案3】:

      实际上,style.heightstyle.width 确实可以使用画布,您也可以将它们设置为不同的大小而不改变内部分辨率,例如在全屏 1024x768 画布上运行 400x300 游戏。

      【讨论】:

      • 如果使用画布样式属性而不是画布元素属性,请确保按比例更改宽度和高度,否则画布上的任何绘图都会水平或垂直扭曲。 ;-)
      • 嗯,有时这正是您想要的。 :)
      猜你喜欢
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多