Image.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. }
  59. this.restoreTransform(ctx); // Draw rect text
  60. if (style.text != null) {
  61. this.drawRectText(ctx, this.getBoundingRect());
  62. }
  63. },
  64. getBoundingRect: function () {
  65. var style = this.style;
  66. if (!this._rect) {
  67. this._rect = new BoundingRect(style.x || 0, style.y || 0, style.width || 0, style.height || 0);
  68. }
  69. return this._rect;
  70. }
  71. };
  72. zrUtil.inherits(ZImage, Displayable);
  73. var _default = ZImage;
  74. module.exports = _default;