【问题标题】:How to fill the whole canvas with specific color?如何用特定颜色填充整个画布?
【发布时间】:2015-01-02 01:09:32
【问题描述】:

如何用一种颜色填充整个 HTML5 <canvas>

我看到了一些解决方案,例如 this 使用 CSS 更改背景颜色,但这不是一个好的解决方案,因为画布保持透明,唯一改变的是它占据的空间的颜色。

另一种方法是在画布内创建带有颜色的东西,例如,一个矩形(see here),但它仍然没有用颜色填充整个画布(如果画布比我们创建的形状大)。

有没有办法用特定颜色填充整个画布?

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    是的,在画布上用纯色填充一个矩形,使用画布本身的heightwidth

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    canvas{ border: 1px solid black; }
    <canvas width=300 height=150 id="canvas">

    【讨论】:

    • 这对我帮助很大!谢谢
    • ctx.fillStyle="rgb(0,0,255)" fillStyle
    【解决方案2】:

    如果你想显式地做背景,你必须确定画布上的当前元素之后。

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    // Add behind elements.
    ctx.globalCompositeOperation = 'destination-over'
    // Now draw!
    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    

    【讨论】:

    • 感谢您意识到人们可能不只是想要一块颜色作为图像!
    • 这实际上应该是destination-under,应该是画布上的第一个操作。
    【解决方案3】:

    您可以通过以下方式更改画布的背景:

    <head>
        <style>
            canvas {
                background-color: blue;
            }
        </style>
    </head>
    

    【讨论】:

    • @Enve 说他或她希望它不使用 CSS。
    • 对 OP 没用。但可能对在标题中搜索问题的人有用。
    【解决方案4】:

    let canvas = document.getElementById('canvas');
    canvas.setAttribute('width', window.innerWidth);
    canvas.setAttribute('height', window.innerHeight);
    let ctx = canvas.getContext('2d');
    
    //Draw Canvas Fill mode
    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0,canvas.width, canvas.height);
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { overflow: hidden; }
    &lt;canvas id='canvas'&gt;&lt;/canvas&gt;

    【讨论】:

      【解决方案5】:

      我们不需要访问画布上下文。

      在纯 JS 中实现 hednek 你会得到 canvas.setAttribute('style', 'background-color:#00F8')。但我首选的方法需要将 kabab-case 转换为 camelCase

      canvas.style.backgroundColor = '#00F8'

      【讨论】:

      • 使用这种方法动态添加形状可能会出现问题
      【解决方案6】:

      你知道吗,有一个完整的画布图形库。它被称为 p5.js 您可以在 head 元素中仅添加一行代码和一个额外的 sketch.js 文件。

      首先对您的 html 和 body 标签执行此操作:

      <html style="margin:0 ; padding:0">
      <body style="margin:0 ; padding:0">
      

      将此添加到您的脑海中:

      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
      <script type="text/javascript" src="sketch.js"></script>
      

      sketch.js 文件

      function setup() {
          createCanvas(windowWidth, windowHeight);
          background(r, g, b);
      }
      

      【讨论】:

      • 请注意,p5.js340kB 最小化压缩的!我想说这个页面包含一些更轻量级的选项..
      • @kano 当我还是个菜鸟时,我写了这个答案。已经很久了。
      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多