Using JavaScript in Smart Pascal

For some tasks JavaScript is easy and it might be quicker to use it (in an asm block) than to find out if/how it has been implemented in Smart Pascal. You need to remember to prefix with a @ any Smart Pascal identifier used in your asm block. We demonstrate here two simple examples in one short program. The first, in procedure ApplicationStarting, uses JavaScript window.prompt() function to return the background colour input by the user. The second asm block, in PaintView, obtains the coordinates of browser window within the screen of the device. Restore down the window and drag the window around the screen to see the coordinates change.

Click here to try the program. If it does not work in your current browser, try another such as Chrome.

The Code

unit Unit1;

interface

uses
  System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application,
  SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics;

type
  TCanvasProject = class(TW3CustomGameApplication)
  private
    colour: String;
  protected
    procedure ApplicationStarting; override;
    procedure ApplicationClosing; override;
    procedure PaintView(Canvas: TW3Canvas); override;
  end;

implementation

procedure TCanvasProject.ApplicationStarting;
begin
  inherited;
  asm
    @colour = window.prompt('Enter background colour:');
  end;
  GameView.Delay := 1;
  GameView.StartSession(False);
 end;

procedure TCanvasProject.ApplicationClosing;
begin
  GameView.EndSession;
  inherited;
end;

procedure TCanvasProject.PaintView(Canvas: TW3Canvas);
var
  scrLeft, scrTop: integer;
begin
  asm
    @scrLeft = window.screenLeft;
    @scrTop = window.screenTop;
  end;
  Canvas.FillStyle := colour;
  Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
  Canvas.Font := '10pt verdana';
  Canvas.FillStyle := 'white';
  Canvas.FillTextF('X coordinate of window on screen: ' + inttostr(scrLeft), 0, 20, MAX_INT);
  Canvas.FillTextF('Y coordinate of window on screen: ' + inttostr(scrTop), 0, 40, MAX_INT);
end;

end.
Programming - a skill for life!

Useful for games, with drawing routines (including transforms and text fonts), images, sprites and WebGL 3D graphics. Now includes Box2D physics and rendering by Pixi.js.