Javascript 如何使用 CSS 设置画布元素的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29675279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to style canvas elements with CSS
提问by Miroslav Nedyalkov
I have a lot of figures and elements drawn in the a HTML canvas. All of them have different colors, strokes, etc. I really don't like that all these values are wandering in my JS code as some styles are in the CSS and some are in the code.
我在 HTML 画布中绘制了很多图形和元素。它们都有不同的颜色、笔触等。我真的不喜欢所有这些值都在我的 JS 代码中徘徊,因为有些样式在 CSS 中,有些在代码中。
Does somebody know a good way to define the styles in CSS and read the styles when actually rendering the objects?
有人知道在 CSS 中定义样式并在实际渲染对象时读取样式的好方法吗?
Here is some example of what I need to do:
这是我需要做的一些示例:
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green'; // I'd like to set with CSS
context.fill();
context.lineWidth = 5; // I'd like to set with CSS
context.strokeStyle = '#003300'; // I'd like to set with CSS
context.stroke();
回答by Asken
I'm a bit late for the party but I just had the same scenario and I solved it like this:
我参加聚会有点晚了,但我遇到了同样的情况,我是这样解决的:
// "Cache"
var classColors = {};
function getColor(className) {
// Check for the color
if (!classColors[className]) {
// Create an element with the class name and add it to the dom
$c = $('<div class="' + className + '"></div>').css('display', 'none');
$(document.body).append($c);
// Get color from dom and put it in the color cache
classColors[className] = $c.css('color');
// Remove the element from the dom again
$c.remove();
}
// Return color
return classColors[className];
}
I only needed the color but you can extend the cache object to hold more than color if you want. The you'd return a full object from the function. The below code is not tested at all:
我只需要颜色,但如果需要,您可以扩展缓存对象以容纳更多颜色。你会从函数中返回一个完整的对象。下面的代码根本没有经过测试:
var classProperties = {};
function getPropeties(className) {
// Check for the properties object
if (!classProperties[className]) {
// Create an element with the class name and add it to the dom
$c = $('<div class="' + className + '"></div>').css('display', 'none');
$(document.body).append($c);
// Get needed stuff from the dom and put it in the cache
// P.S. Didn't test if canvas names are the same as css names.
// If not you'll have to translate it
classProperties[className] = {
fillStyle: $c.css('color'),
lineWidth: $c.css('border-width'),
strokeStyle: $c.css('border-style')
}
// Remove the element from the dom again
$c.remove();
}
// Return properties
return classProperties[className];
}
回答by Domino
Normally, people who draw a lot of stuff in a canvas will make their own shape objects with style properties. For example: http://jsfiddle.net/b93cc3ww/
通常,在画布中绘制大量内容的人会制作自己的具有样式属性的形状对象。例如:http: //jsfiddle.net/b93cc3ww/
context = document.getElementById("myCanvas").getContext("2d");
function Rectangle(params) {
this.x = params.x || 0;
this.y = params.y || 0;
this.width = params.width || 0;
this.height = params.height || 0;
this.fillStyle = params.fillStyle || "#FFFFFF";
this.strokeStyle = params.strokeStyle || "#000000";
this.lineWidth = params.lineWidth || 0;
}
Rectangle.prototype.draw = function () {
if (this.fillStyle) {
context.fillStyle = this.fillStyle;
context.fillRect(this.x, this.y, this.width, this.height)
}
if (this.strokeStyle && this.lineWidth) {
context.strokeStyle = this.strokeStyle;
context.lineWidth = this.lineWidth;
context.strokeRect(this.x, this.y, this.width, this.height);
}
}
rectangles = [
new Rectangle({
x: 10,
y: 10,
width: 300,
height: 150,
fillStyle: "#FF0000"
}),
new Rectangle({
x: 250,
y: 10,
width: 100,
height: 80,
fillStyle: "#00FF00",
strokeStyle: "#00AA00",
lineWidth: 5
}),
new Rectangle({
x: 10,
y: 200,
width: 250,
height: 80,
strokeStyle: "#FF0000",
lineWidth: 1
})
]
for (var i = 0; i < rectangles.length; ++i) {
rectangles[i].draw();
}
If you like the way CSS works, you could make a shape object which can take a "class" parameter and then store a list of "clases" in an array at the top of your code.
如果你喜欢 CSS 的工作方式,你可以创建一个形状对象,它可以接受一个“类”参数,然后将“类”列表存储在代码顶部的数组中。
回答by Elad Stern
CSS has a certain scope to it, that is, it only acts on HTML elements. Javascript, on the other hand, has its own variables and can also interact with HTML elements. What you're trying to do is use CSS as variables for javascript, which can't be done.
CSS 有一定的作用域,即它只作用于 HTML 元素。另一方面,Javascript 有自己的变量,也可以与 HTML 元素交互。您想要做的是使用 CSS 作为 javascript 的变量,这是无法完成的。
The code sample above represents a piece of javascript which takes an HTML element (in this case a canvas) and performs a set of actions (methods) on it. What you're doing is literally drawing one line at a time to create your image, and this image is outside of the CSS scope as it is only defined by the elements internal properties, while CSS can only define its external (specifically, visual) properties.
上面的代码示例表示一段 javascript,它接受一个 HTML 元素(在本例中为 a canvas)并对其执行一组操作(方法)。你所做的实际上是一次画一条线来创建你的图像,这个图像在 CSS 范围之外,因为它只由元素内部属性定义,而 CSS 只能定义它的外部(特别是视觉)特性。

