我可以使用 css 中的变量设置画布 fillStyle 吗?

idb*_*rii 5 html javascript css

如何使用css 变量来设置画布颜色?

例子:

<html>
  <head>
    <style>
:root {
  --color-bright:#ffca00;
  --color-bg:#40332e;
}

body {
  background-color: var(--color-bg);
  color: var(--color-bright);
}

    </style>
  </head>
  <body>
    <center>
      <div>
        <canvas id="loadingCanvas" oncontextmenu="event.preventDefault()" width="800" height="600"></canvas>
      </div>
    </center>

    This text is actually yellowish.

    <script type='text/javascript'>
      var loadingContext = document.getElementById('loadingCanvas').getContext('2d');
      var canvas = loadingContext.canvas;

      loadingContext.fillStyle = "rgb( 0, 0, 0 )";
      // Doesn't work (should be brown instead of black):
      loadingContext.fillStyle = "var(--color-bg)";
      loadingContext.fillRect(0, 0, canvas.scrollWidth, canvas.scrollHeight);

      loadingContext.font = '30px sans-serif';
      loadingContext.textAlign = 'center'
      loadingContext.fillStyle = "rgb( 200, 200, 200 )";
      // Doesn't work (should be yellow instead of white):
      loadingContext.fillStyle = "var(--color-bright)";
      loadingContext.fillText("This text should be yellowish.", canvas.scrollWidth / 2, canvas.scrollHeight / 2);
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 7

不,你不能,至少目前不能。我必须承认,我不能 100% 确定它是否应该工作,导航 CSS解析语法对我来说现在相当复杂,但无论如何,没有浏览器支持它,所以即使规范实际上告诉它它应该可以工作,但规格将是错误的(我将进一步调查这一点,也许会在那里提出一个问题)。

请注意,很明显这currentColor应该可行,而且确实在 Firefox 中可行,但在 Blink 和 WebKit 中都不是,所以最好认为它不受支持。

但是,您可以做的是通过调用自己获取解析值getComputedStyle(context.canvas).getPropertyValue("--the-property"):

const loadingContext = document.getElementById('loadingCanvas').getContext('2d');
const canvas = loadingContext.canvas;

loadingContext.fillStyle = "rgb( 0, 0, 0 )";

loadingContext.fillStyle = getComputedStyle(canvas).getPropertyValue("--color-bg");
loadingContext.fillRect(0, 0, canvas.scrollWidth, canvas.scrollHeight);

loadingContext.font = '30px sans-serif';
loadingContext.textAlign = 'center'
loadingContext.fillStyle = "rgb( 200, 200, 200 )";

loadingContext.fillStyle = getComputedStyle(canvas).getPropertyValue("--color-bright");
loadingContext.fillText("This text should be yellowish.", canvas.scrollWidth / 2, canvas.scrollHeight / 2);
Run Code Online (Sandbox Code Playgroud)
:root {
  --color-bright:#ffca00;
  --color-bg:#40332e;
}

body {
  background-color: var(--color-bg);
  color: var(--color-bright);
}
Run Code Online (Sandbox Code Playgroud)
<canvas id="loadingCanvas" width="800" height="600"></canvas>

This text is actually yellowish.
Run Code Online (Sandbox Code Playgroud)

请注意,即使它确实按照您想要的方式工作,该值也只会在设置属性时进行解析,因此这样做的效果完全相同,而且,这显然不适用于未在属性中连接的画布DOM。

PS:Chrome 和 Safari 实际上支持设置fillStyleto "currentColor",但仅当颜色设置为直接颜色( no currentColor,nor var(--prop)),以及设置为 canvas 元素的style属性时(不通过样式表或继承)。在我看来,这是相当糟糕的,我将提出几个问题,至少让这个工作正常进行。