1 /** 2 * Hilo 3 * Copyright 2015 alibaba.com 4 * Licensed under the MIT License 5 */ 6 7 /** 8 * @class Drawable is a wrapper of drawable images. 9 * @param {Object} properties create Objects properties, contains all writable properties. 10 * @module hilo/view/Drawable 11 * @requires hilo/core/Class 12 * @requires hilo/util/util 13 * @property {Object} image Image to be drawed, can used by CanvasRenderingContext2D.drawImage,like HTMLImageElement、HTMLCanvasElement、HTMLVideoElement。 14 * @property {array} rect The retangle area that image will be drawed. 15 */ 16 var Drawable = Class.create(/** @lends Drawable.prototype */{ 17 constructor: function(properties){ 18 this.init(properties); 19 }, 20 21 image: null, 22 rect: null, 23 24 /** 25 * Initialize drawable elements. 26 * @param {Object} properties Properties need to be initialized. 27 */ 28 init: function(properties){ 29 var me = this, oldImage = me.image; 30 if(Drawable.isDrawable(properties)){ 31 me.image = properties; 32 }else{ 33 util.copy(me, properties, true); 34 } 35 36 var image = me.image; 37 if(typeof image === 'string'){ 38 if(oldImage && image === oldImage.getAttribute('src')){ 39 image = me.image = oldImage; 40 }else{ 41 me.image = null; 42 //load image dynamically 43 var img = new Image(); 44 if(properties.crossOrigin){ 45 img.crossOrigin = "Anonymous"; 46 } 47 img.onload = function(){ 48 img.onload = null; 49 me.init(img); 50 }; 51 img.src = image; 52 return; 53 } 54 } 55 56 if(image && !me.rect) me.rect = [0, 0, image.width, image.height]; 57 }, 58 59 Statics: /** @lends Drawable */{ 60 /** 61 * Check whether the given 'elem' and be wrapped into Drawable object. 62 * @param {Object} elem Element to be tested. 63 * @return {Boolean} Return true if element can be wrapped into Drawable element, otherwises return false. 64 */ 65 isDrawable: function(elem){ 66 if(!elem || !elem.tagName) return false; 67 var tagName = elem.tagName.toLowerCase(); 68 return tagName === "img" || tagName === "canvas" || tagName === "video"; 69 } 70 } 71 });