缩放SVG图像以适合父级并在不同实例中更改仪表颜色

时间:2016-04-06 12:53:52

标签: javascript svg raphael

我正在尝试使用Raphael执行以下操作:

1)缩放SVG以适合父div(在本例中为#bg

2)在不同情况下更改仪表的颜色......这是我迄今为止所做的,但它不起作用:

archtype.customAttributes.counter = function (counter, top) {
  var motto = '';
  switch(true) {
    case(counter<=(top/10)):
      motto = 'Very Poor !'
      colour = '#BD2727'; //pretty sure this is wrong
      break;
    case(counter<=(5.61*top/10)):
      motto = 'Poor'
      colour = '#F79A38'; //pretty sure this is wrong
      break;
    case(counter<=(7.21*top/10)):
      motto = 'Fair'
      colour = '#FBDE07'; //pretty sure this is wrong
      break;    
    case(counter<=(8.81*top/10)):
      motto = 'Good'
      colour = '#90C342'; //pretty sure this is wrong
      break;
    case(counter<=(9.61*top/10)):
      motto = 'Excellent'
      colour = '#1F9C4C'; //pretty sure this is wrong
      break;       
  }
  return {
    counter: [counter,top],
    text: Math.floor(counter) + '\n' + motto
  }
}

在这里小提琴:http://jsfiddle.net/mwvLc0kb/4/

1 个答案:

答案 0 :(得分:1)

我希望我的回答不会太晚:

1)适合容器可能在IE上很棘手,但在Chr / FF上更容易:你必须执行以下操作(参见my responsive gauge lib):

  • 添加viewBox =&#34; 0 0 w h&#34; preserveAspectRatio =&#34; xMinYMin meet&#34;到svg节点。不需要w和h作为像素大小,它们只设置比率:对于正方形,w = h = 1,
  • 将高度= 100%和最大宽度= 100%添加到svg节点CSS,
  • 当然,为svg父div设置高度或宽度,
  • 对于IE,添加一个画布和svg节点,否则它将不会正确调整svg的大小。

请注意,在窗口调整大小期间调整仪表的大小在IE上更加棘手......

2)您必须在弧的属性上设置颜色,而不是计数器的属性,请参阅this fiddle

archtype.customAttributes.arc = function(xloc, yloc, value, total, R, counter, top) {
  var alpha = 360 / total * value,
  a = (90 - alpha) * Math.PI / 180,
  x = xloc + R * Math.cos(a),
  y = yloc - R * Math.sin(a),
  path;

  if (total == value) {
    path = [
      ["M", xloc, yloc - R],
      ["A", R, R, 0, 1, 1, xloc - 0.01, yloc - R]
    ];
  } else {
    path = [
      ["M", xloc, yloc - R],
      ["A", R, R, 0, +(alpha > 180), 1, x, y]
    ];
  }

  if (counter && top) {
    var colour;
    switch (true) {
      case (counter <= (top / 10)):
        colour = '#BD2727'; //pretty sure this is wrong
        break;
      case (counter <= (5.61 * top / 10)):
        colour = '#F79A38'; //pretty sure this is wrong
        break;
      case (counter <= (7.21 * top / 10)):
        colour = '#FBDE07'; //pretty sure this is wrong
        break;
      case (counter <= (8.81 * top / 10)):
        colour = '#90C342'; //pretty sure this is wrong
        break;
      case (counter <= (9.61 * top / 10)):
        colour = '#1F9C4C'; //pretty sure this is wrong
        break;
    }
  }

  var result = {
    path: path
  };
  if (colour){
    result.stroke = colour;
  }

  return result;
};