猿问

为什么笔触颜色没有改变?

我希望每个绘制的正方形的颜色都改变。也许它与rgb有关?但我真的很陌生,所以我真的不知道哈哈。


不知道还有什么可以尝试的。


<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title>IDK</title>

    <style>

      body {

        background-color:rgb(30, 30, 30);

        color:White;

      }

    </style>

  </head>

  <body>

    <h2>IDK</h2>

    <canvas id="minCanvas" width="600" height="600"></canvas>

    <script>

      var canvas = document.getElementById("minCanvas");

      var ctx = canvas.getContext("2d");

      var side=600;

      var x=0;

      var y=0;

      var a = 255;

      var b = 255;

      var c = 255;

      while (side>0) {

        ctx.strokeStyle = "rgb(a,b,c)";

        ctx.strokeRect(x, y, side, side);

        //ctx.stroke();

        a-=50;

        b-=10;

        c-=30;

        x+=5;

        y+=5;

        side-=10;

      }

    </script>

  </body>

</html>


呼啦一阵风
浏览 139回答 1
1回答

有只小跳蛙

您必须显式地将变量插入到 rgb 字符串中:ctx.strokeStyle = "rgb("+a+","+b+","+c+")"如果支持,您还可以使用模板字符串:ctx.strokeStyle = `rgb(${a},${b},${c})`&nbsp; &nbsp; &nbsp; var canvas = document.getElementById("minCanvas");&nbsp; &nbsp; &nbsp; var ctx = canvas.getContext("2d");&nbsp; &nbsp; &nbsp; var side=600;&nbsp; &nbsp; &nbsp; var x=0;&nbsp; &nbsp; &nbsp; var y=0;&nbsp; &nbsp; &nbsp; var a = 255;&nbsp; &nbsp; &nbsp; var b = 255;&nbsp; &nbsp; &nbsp; var c = 255;&nbsp; &nbsp; &nbsp; while (side>0) {&nbsp; &nbsp; &nbsp; &nbsp; ctx.strokeStyle = "rgb("+a+","+b+","+c+")";&nbsp; &nbsp; &nbsp; &nbsp; ctx.strokeRect(x, y, side, side);&nbsp; &nbsp; &nbsp; &nbsp; //ctx.stroke();&nbsp; &nbsp; &nbsp; &nbsp; a-=50;&nbsp; &nbsp; &nbsp; &nbsp; b-=10;&nbsp; &nbsp; &nbsp; &nbsp; c-=30;&nbsp; &nbsp; &nbsp; &nbsp; x+=5;&nbsp; &nbsp; &nbsp; &nbsp; y+=5;&nbsp; &nbsp; &nbsp; &nbsp; side-=10;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; body {&nbsp; &nbsp; &nbsp; &nbsp; background-color:rgb(30, 30, 30);&nbsp; &nbsp; &nbsp; &nbsp; color:White;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; <h2>IDK</h2>&nbsp; &nbsp; <canvas id="minCanvas" width="600" height="600"></canvas>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答