Image.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. var Displayable = require("./Displayable");
  2. var BoundingRect = require("../core/BoundingRect");
  3. var zrUtil = require("../core/util");
  4. var imageHelper = require("./helper/image");
  5. /**
  6. * @alias zrender/graphic/Image
  7. * @extends module:zrender/graphic/Displayable
  8. * @constructor
  9. * @param {Object} opts
  10. */
  11. function ZImage(opts) {
  12. Displayable.call(this, opts);
  13. }
  14. ZImage.prototype = {
  15. constructor: ZImage,
  16. type: 'image',
  17. brush: function (ctx, prevEl) {
  18. var style = this.style;
  19. var src = style.image; // Must bind each time
  20. style.bind(ctx, this, prevEl);
  21. var image = this._image = imageHelper.createOrUpdateImage(src, this._image, this, this.onload);
  22. if (!image || !imageHelper.isImageReady(image)) {
  23. return;
  24. } // 图片已经加载完成
  25. // if (image.nodeName.toUpperCase() == 'IMG') {
  26. // if (!image.complete) {
  27. // return;
  28. // }
  29. // }
  30. // Else is canvas
  31. var x = style.x || 0;
  32. var y = style.y || 0;
  33. var width = style.width;
  34. var height = style.height;
  35. var aspect = image.width / image.height;
  36. if (width == null && height != null) {
  37. // Keep image/height ratio
  38. width = height * aspect;
  39. } else if (height == null && width != null) {
  40. height = width / aspect;
  41. } else if (width == null && height == null) {
  42. width = image.width;
  43. height = image.height;
  44. } // 设置transform
  45. this.setTransform(ctx);
  46. if (style.sWidth && style.sHeight) {
  47. var sx = style.sx || 0;
  48. var sy = style.sy || 0;
  49. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  50. } else if (style.sx && style.sy) {
  51. var sx = style.sx;
  52. var sy = style.sy;
  53. var sWidth = width - sx;
  54. var sHeight = height - sy;
  55. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  56. } else {
  57. ctx.drawImage(image, x, y, width, height);
  58. } // Draw rect text
  59. if (style.text != null) {
  60. // Only restore transform when needs draw text.
  61. this.restoreTransform(ctx);
  62. this.drawRectText(ctx, this.getBoundingRect());
  63. }
  64. },
  65. getBoundingRect: function () {
  66. var style = this.style;
  67. if (!this._rect) {
  68. this._rect = new BoundingRect(style.x || 0, style.y || 0, style.width || 0, style.height || 0);
  69. }
  70. return this._rect;
  71. }
  72. };
  73. zrUtil.inherits(ZImage, Displayable);
  74. var _default = ZImage;
  75. module.exports = _default;