gradutils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Various generic utilities to deal with a linear gradient
  2. define("dojox/gfx/gradutils", ["./_base", "dojo/_base/lang", "./matrix", "dojo/_base/Color"],
  3. function(g, lang, m, Color){
  4. /*===== g= dojox.gfx =====*/
  5. var gradutils = g.gradutils = {};
  6. /*===== g= dojox.gfx; gradutils = dojox.gfx.gradutils; =====*/
  7. function findColor(o, c){
  8. if(o <= 0){
  9. return c[0].color;
  10. }
  11. var len = c.length;
  12. if(o >= 1){
  13. return c[len - 1].color;
  14. }
  15. //TODO: use binary search
  16. for(var i = 0; i < len; ++i){
  17. var stop = c[i];
  18. if(stop.offset >= o){
  19. if(i){
  20. var prev = c[i - 1];
  21. return Color.blendColors(new Color(prev.color), new Color(stop.color),
  22. (o - prev.offset) / (stop.offset - prev.offset));
  23. }
  24. return stop.color;
  25. }
  26. }
  27. return c[len - 1].color;
  28. }
  29. gradutils.getColor = function(fill, pt){
  30. // summary:
  31. // sample a color from a gradient using a point
  32. // fill: Object:
  33. // fill object
  34. // pt: dojox.gfx.Point:
  35. // point where to sample a color
  36. var o;
  37. if(fill){
  38. switch(fill.type){
  39. case "linear":
  40. var angle = Math.atan2(fill.y2 - fill.y1, fill.x2 - fill.x1),
  41. rotation = m.rotate(-angle),
  42. projection = m.project(fill.x2 - fill.x1, fill.y2 - fill.y1),
  43. p = m.multiplyPoint(projection, pt),
  44. pf1 = m.multiplyPoint(projection, fill.x1, fill.y1),
  45. pf2 = m.multiplyPoint(projection, fill.x2, fill.y2),
  46. scale = m.multiplyPoint(rotation, pf2.x - pf1.x, pf2.y - pf1.y).x;
  47. o = m.multiplyPoint(rotation, p.x - pf1.x, p.y - pf1.y).x / scale;
  48. break;
  49. case "radial":
  50. var dx = pt.x - fill.cx, dy = pt.y - fill.cy;
  51. o = Math.sqrt(dx * dx + dy * dy) / fill.r;
  52. break;
  53. }
  54. return findColor(o, fill.colors); // dojo.Color
  55. }
  56. // simple color
  57. return new Color(fill || [0, 0, 0, 0]); // dojo.Color
  58. };
  59. gradutils.reverse = function(fill){
  60. // summary:
  61. // reverses a gradient
  62. // fill: Object:
  63. // fill object
  64. if(fill){
  65. switch(fill.type){
  66. case "linear":
  67. case "radial":
  68. fill = lang.delegate(fill);
  69. if(fill.colors){
  70. var c = fill.colors, l = c.length, i = 0, stop,
  71. n = fill.colors = new Array(c.length);
  72. for(; i < l; ++i){
  73. stop = c[i];
  74. n[i] = {
  75. offset: 1 - stop.offset,
  76. color: stop.color
  77. };
  78. }
  79. n.sort(function(a, b){ return a.offset - b.offset; });
  80. }
  81. break;
  82. }
  83. }
  84. return fill; // Object
  85. };
  86. return gradutils;
  87. });