在 Firefox WebExtension 中更改 SVG 工具栏图标的颜色

Change Color Of SVG toolbar icon in Firefox WebExtension

我正在使用 WebExtensions 为 Firefox 57+ 开发一个扩展。我想更改工具栏图标的颜色以指示扩展状态。

我明白如何,如本 answer 中所述,我可以简单地使用 browserAction.setIcon() 更改图标并替换为不同颜色的图标。

我想知道我是否真的需要在我的扩展程序中包含 icon-black.svg、icon-red.svg 等文件,或者是否有某种方法可以简单地加载单个 icon.svg 文件并使用 javascript 更改图像的颜色。我希望我能以某种方式以编程方式加载它并在将它传递给 browserAction.setIcon() 之前修改 svg 的颜色(即所有路径)。我是否需要以某种方式将其加载到某种 canvas 类型的元素中才能执行此操作?我什至可以在扩展程序中执行此操作吗?

是的,您可以在扩展程序中执行此操作

browserAction.setIcon() documentation states that the Object which is passed to the method will contain either a path to the icon file within your extension (or an Object containing multiple such paths with different sizes), or an imageData, which is a browserAction.ImageDataType, which is an ImageData(或指定多个具有不同大小的此类项目的对象):

The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData(). It can also be used to set a part of the canvas by using putImageData().

这样CanvasRenderingContext2D可以用一个SVGImageElement as a source to draw an image using CanvasRenderingContext2D.drawImage().

所以,是的,您可以在扩展程序中执行此操作。而且,是的,您需要将其加载到 "canvas type element" 中才能执行此操作。

更改图标徽章文本和颜色更容易

使用图标徽章并更改 background color and text of the badge. Doing so might make for a better UX, as icon badges are the UI element specifically intended to transmit such sate-change information to users. You should also change the badge title 以指示下一次单击该图标将执行的操作会简单得多。

只改颜色不好UI设计

仅仅改变图标的​​颜色来指示状态并不是一个好的用户界面设计。这样做会使视力不佳的人(例如色盲、使用屏幕 reader 等)难以使用该界面。至少,除了图标颜色之外,您应该更改一些明显可见的内容(例如形状、徽章文本等)。 应该 还包括一些变化,屏幕 readers 也检测到这些变化。

作为这导致的问题类型的示例,以下是 Stack Exchange 使用仅更改某些通知的成就图标颜色的讨论:Change the color of the "achievements" icon when it's highlighted (for users with Deuteranopia)