是否可以将从画布上下文创建的渐变应用于其他画布上下文

Can I apply gradients created from a canvas context to other canvas contexts?

本文关键字:上下文 渐变 应用于 其他 创建 是否      更新时间:2023-09-26

是否可以将从画布上下文创建的渐变应用于其他画布上下文,如以下代码所示?

var canvasContextA = document.getElementById("canvasA").getContext("2d");
var canvasContextB = document.getElementById("canvasB").getContext("2d");
var gradientFromCanvasContextA = canvasContextA.createLinearGradient(0, 0, 100, 0);
gradientFromCanvasContextA.addColorStop(0, "black");
gradientFromCanvasContextA.addColorStop(1, "white");
canvasContextB.fillStyle = gradientFromCanvasContextA;

你能根据标准给我一个答案吗?这是一种未定义的行为吗?

有趣的问题。我在 Canvas 2D 规格中找到了这个注释:

In the case of addColorStop() on CanvasGradient, the "computed value of the 'color' property" for the purposes of determining the computed value of the currentColor keyword is always fully opaque black (there is no associated element). [CSSCOLOR]
This is because CanvasGradient objects are canvas-neutral — a CanvasGradient object created by one canvas can be used by another, and there is therefore no way to know which is the "element in question" at the time that the color is specified.

似乎暗示您可以按照要求进行操作,但仅适用于渐变和可能的字体属性。