canvasTransforms.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function attachTransforms(ctx) {
  2. var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
  3. var xform = svg.createSVGMatrix();
  4. ctx.getTransform = function(){ return xform; };
  5. var savedTransforms = [];
  6. var save = ctx.save;
  7. ctx.save = function(){
  8. savedTransforms.push(xform.translate(0,0));
  9. return save.call(ctx);
  10. };
  11. var restore = ctx.restore;
  12. ctx.restore = function(){
  13. xform = savedTransforms.pop();
  14. return restore.call(ctx);
  15. };
  16. var scale = ctx.scale;
  17. ctx.scale = function(sx,sy){
  18. xform = xform.scaleNonUniform(sx,sy);
  19. return scale.call(ctx,sx,sy);
  20. };
  21. var rotate = ctx.rotate;
  22. ctx.rotate = function(radians){
  23. xform = xform.rotate(radians*180/Math.PI);
  24. return rotate.call(ctx,radians);
  25. };
  26. var translate = ctx.translate;
  27. ctx.translate = function(dx,dy){
  28. xform = xform.translate(dx,dy);
  29. return translate.call(ctx,dx,dy);
  30. };
  31. var transform = ctx.transform;
  32. ctx.transform = function(a,b,c,d,e,f){
  33. var m2 = svg.createSVGMatrix();
  34. m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
  35. xform = xform.multiply(m2);
  36. return transform.call(ctx,a,b,c,d,e,f);
  37. };
  38. var setTransform = ctx.setTransform;
  39. ctx.setTransform = function(a,b,c,d,e,f){
  40. xform.a = a;
  41. xform.b = b;
  42. xform.c = c;
  43. xform.d = d;
  44. xform.e = e;
  45. xform.f = f;
  46. return setTransform.call(ctx,a,b,c,d,e,f);
  47. };
  48. var pt = svg.createSVGPoint();
  49. ctx.transformedPoint = function(x,y){
  50. pt.x=x; pt.y=y;
  51. return pt.matrixTransform(xform.inverse());
  52. };
  53. }