subPixelOptimize.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var round = Math.round;
  2. export function subPixelOptimizeLine(outputShape, inputShape, style) {
  3. if (!inputShape) {
  4. return;
  5. }
  6. var x1 = inputShape.x1;
  7. var x2 = inputShape.x2;
  8. var y1 = inputShape.y1;
  9. var y2 = inputShape.y2;
  10. outputShape.x1 = x1;
  11. outputShape.x2 = x2;
  12. outputShape.y1 = y1;
  13. outputShape.y2 = y2;
  14. var lineWidth = style && style.lineWidth;
  15. if (!lineWidth) {
  16. return outputShape;
  17. }
  18. if (round(x1 * 2) === round(x2 * 2)) {
  19. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  20. }
  21. if (round(y1 * 2) === round(y2 * 2)) {
  22. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  23. }
  24. return outputShape;
  25. }
  26. export function subPixelOptimizeRect(outputShape, inputShape, style) {
  27. if (!inputShape) {
  28. return;
  29. }
  30. var originX = inputShape.x;
  31. var originY = inputShape.y;
  32. var originWidth = inputShape.width;
  33. var originHeight = inputShape.height;
  34. outputShape.x = originX;
  35. outputShape.y = originY;
  36. outputShape.width = originWidth;
  37. outputShape.height = originHeight;
  38. var lineWidth = style && style.lineWidth;
  39. if (!lineWidth) {
  40. return outputShape;
  41. }
  42. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  43. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  44. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  45. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  46. return outputShape;
  47. }
  48. export function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  49. if (!lineWidth) {
  50. return position;
  51. }
  52. var doubledPosition = round(position * 2);
  53. return (doubledPosition + round(lineWidth)) % 2 === 0
  54. ? doubledPosition / 2
  55. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  56. }