gpt4 book ai didi

javascript - 我可以使用 css 中的变量设置 Canvas fillStyle 吗?

转载 作者:行者123 更新时间:2023-12-05 03:27:49 26 4
gpt4 key购买 nike

如何使用 css variables设置 Canvas 颜色?

例子:

<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>

最佳答案

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

请注意,很明显 currentColor should work ,在 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);
:root {
--color-bright:#ffca00;
--color-bg:#40332e;
}

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

This text is actually yellowish.

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

Ps: Chrome 和 Safari 实际上支持将 fillStyle 设置为 "currentColor",但仅当颜色设置为直接颜色时(没有 currentColor ,也不是 var(--prop)),当设置为 canvas 元素的 style 属性时(不是通过样式表也不是继承)。这在 IMO 中非常糟糕,我将打开几个问题以至少让它正常工作。

关于javascript - 我可以使用 css 中的变量设置 Canvas fillStyle 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71368314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com