babylon.dynamicTexture.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module BABYLON {
  2. export class DynamicTexture extends Texture {
  3. private _generateMipMaps: boolean;
  4. private _canvas: HTMLCanvasElement;
  5. private _context: CanvasRenderingContext2D;
  6. constructor(name: string, options: any, scene: Scene, generateMipMaps: boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) {
  7. super(null, scene, !generateMipMaps);
  8. this.name = name;
  9. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11. this._generateMipMaps = generateMipMaps;
  12. if (options.getContext) {
  13. this._canvas = options;
  14. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15. } else {
  16. this._canvas = document.createElement("canvas");
  17. if (options.width) {
  18. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19. } else {
  20. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21. }
  22. }
  23. var textureSize = this.getSize();
  24. this._canvas.width = textureSize.width;
  25. this._canvas.height = textureSize.height;
  26. this._context = this._canvas.getContext("2d");
  27. }
  28. public getContext(): CanvasRenderingContext2D {
  29. return this._context;
  30. }
  31. public update(invertY?: boolean): void {
  32. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  33. }
  34. public drawText(text: string, x: number, y: number, font: string, color: string, clearColor: string, invertY?: boolean) {
  35. var size = this.getSize();
  36. if (clearColor) {
  37. this._context.fillStyle = clearColor;
  38. this._context.fillRect(0, 0, size.width, size.height);
  39. }
  40. this._context.font = font;
  41. if (x === null) {
  42. var textSize = this._context.measureText(text);
  43. x = (size.width - textSize.width) / 2;
  44. }
  45. this._context.fillStyle = color;
  46. this._context.fillText(text, x, y);
  47. this.update(invertY);
  48. }
  49. public clone(): DynamicTexture {
  50. var textureSize = this.getSize();
  51. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  52. // Base texture
  53. newTexture.hasAlpha = this.hasAlpha;
  54. newTexture.level = this.level;
  55. // Dynamic Texture
  56. newTexture.wrapU = this.wrapU;
  57. newTexture.wrapV = this.wrapV;
  58. return newTexture;
  59. }
  60. }
  61. }