如何使用CSS设置画布元素的样式 [英] How to style canvas elements with CSS
问题描述
我在HTML画布中绘制了很多图形和元素.它们都有不同的颜色,笔触等.我真的不喜欢所有这些值都在我的JS代码中徘徊,因为某些样式在CSS中,而某些样式在代码中.
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.
在实际渲染对象时,有人知道在CSS中定义样式并读取样式的好方法吗?
Does somebody know a good way to define the styles in CSS and read the styles when actually rendering the objects?
这是我需要做的一些例子:
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();
http://jsfiddle.net/nedyalkov/ysgLqqh3/1/
推荐答案
我参加聚会有点晚了,但我的情况是一样的,所以我这样解决了它:
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];
}
这篇关于如何使用CSS设置画布元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!