zimjs
Version:
JavaScript Canvas Framework - Code Creativity!<br> https://zimjs.com
761 lines (690 loc) • 1.66 MB
Markdown
ZIM DOCS 018
http://zimjs.com/docs.html
http://zimjs.com/updates.html
http://zimjs.com/tips.html
http://zimjs.com/bits.html
A. ABOUT ZIM
ZIM is an JavaScript Canvas Framework powered by CreateJS and adds many components, conveniences and controls for making general Interactive Media.
The ZIM site at http://zimjs.com features the following sections:
LEARN tutorials on how to start and code in ZIM
EDITOR online editor with lots of Zapps for reference
CODE the template, tools and libraries
STORE examples of ZIM mobile PWA apps
DOCS the objects and commands all defined
ABOUT features, applications, archives, reviews, etc.
EXAMPLES sample projects created in ZIM
GOLD BARS with intro, site map, tips, resources and sharing tool
B. ABOUT THE DOCS
The docs are divided into modules:
FRAME, DISPLAY, METHODS, CONTROLS, CODE, WRAP, META, LIBRARIES
Let's have a brief look at each...
---------------------------------
1. FRAME - the framework class that makes and scales the canvas and stage
new Frame(FIT, 1024, 768, light, dark, ready, ["pic.png", "sound.mp3"]);
function ready() {
// given F, S, W, H - for frame, stage, stageW, stageH
const aud = new Aud("sound.mp3");
const pic = new Pic(pic.png).center().tap(()=>{
aud.play();
});
} // end ready
---------------------------------
3. DISPLAY - classes for objects viewed on the stage like shapes and components
const circle = new Circle(100, "red"); // also Rectangle, Triangle and Blob
const button = new Button(200, 100, "GO!");
etc. and dozens more like Label, Slider, Dial, Tabs, ColorPicker...
---------------------------------
4. METHODS - methods for the display objects above
circle.center(); // adds to and centers button on stage
circle.drag(); // allows the circle to be dragged and dropped
circle.animate(props:{alpha:0}, 5); // fades out circle over 5 seconds
etc. and dozens more - also see PRINCIPLES sections below...
---------------------------------
5. CONTROLS - classes that affect Display objects
new MotionController(circle); // circle moves to mouse press
new Pages([home, help]); // handle pages and swiping
new Layout(S, [{object:header},{object:content},{object:footer}]);
responsive design with many more options (like css flex table)
etc. including Parallax, Scroller, Guide, Grid, Emitter, SoundWave...
---------------------------------
5. CODE - non-Canvas code convienence functions
const array = ["red", "yellow", "green", "blue"];
let color = pluck(array); // gets a random element
let color = shuffle(array)[0]; // shuffles array and picks first color (same as above)
let color = array[rand(array.length-1)]; // gets random element (same as above)
etc. many more including browser functions and asynchronus calls
---------------------------------
6. WRAP - a dozen three-letter global functions starting with z
zog("hello world"); // short for console.log();
zid("tagID"); // short for document.getElementById();
etc. including selectors similar to $() in jQuery
---------------------------------
7. META - a few classes and functions operating on zim
DISTILL = true;
distill(); // writes to console all the commands used to reduce code
zimify(createjsObj); // adds zim Methods to native createjs display objects
wonder.count("wow"); // once set up records different types of stats
---------------------------------
8. LIBRARIES - other ZIM helper modules found here:
http://zimjs.com/code.html#libraries
Including: SOCKET, GAME, PHYSICS, THREE, CAM, PIZZAZZ 1, 2 and 3 modules
C. THE DOCS
------------------------------------
MODULE 1: ZIM FRAME
------------------------------------
************************************
[86277] Frame(scaling, width, height, color, outerColor, ready, assets, path, progress, ticker, rollover, touch, scrollTop, align, valign, canvasID, rollPerSecond, delay, canvasCheck, gpu, gpuObj, nextFrame, nextStage, allowDefault, loadFailObj, retina, mouseMoveOutside, captureMouse, shim, maxConnections, maxNum, singleTouch)
Frame
zim class - extends a createjs EventDispatcher
DESCRIPTION
Frame creates a canvas and stage.
Frame lets you decide how you want your stage to scale.
It also provides events for ready, resizing and orientation change
as well as a way to remake the canvas if necessary.
Frame handles loading Bitmap, Sound, etc. assets by wrapping PreloadJS
See https://zimjs.com/frame.html for sample templates using Frame.
The first frame made is called the zimDefaultFrame - or zdf.
It will also have the default stage for addTo(), center(), etc.
Use setDefault() on another frame to change the default frame.
As of ZIM ZIM 01, ZIM will make F, S, W, H global variables
that reference the zimDefaultFrame, its stage and the stage width and height.
The width and height will be updated in FULL mode if the window size changes.
ZIM ASSET TOOL
See https://zimjs.com/assetlist/
Optionally use this tool to prepare an array of assets from a folder.
CANVAS ALTERNATIVE CONTENT
Frame will move any tag with an id of canvasIDAlternative into the canvas tag.
By default, the canvasID is "myCanvas" so use an id of "myCanvasAlternative".
This allows you to show content for non-canvas browsers.
The content may also be indexed by search engines - one would hope
and is read by screen readers (see also ZIM Accessibility).
NOTE: addTo(), center(), centerReg(), loc(), pos(), new Ticker.add()
default to the stage of the first frame made
use the setDefault() method to set a frame to the default frame
NOTE: here are some tips that relate to Frame:
https://zimjs.com/tips#FRAME
https://zimjs.com/tips#IMAGES
https://zimjs.com/tips#SOUND
https://zimjs.com/tips#FULLSCREEN
NOTE: as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// load assets such as images right in Frame call using a url
// put multiple assets in an array - see assets parameter for options
// the path and progress are optional
new Frame(FIT, 1024, 768, "#ddd", "#333", ready, "image.png", "assets/", new Waiter());
function ready() {
new Pic("image.png").center(); // formerly had used asset("image.png").center();
} // end ready
EXAMPLE
// load assets on-demand inside ready event
new Frame(FIT, 1024, 768, dark, light, ready);
function ready() {
// code here - or optionally load assets
F.loadAssets("image.png");
F.on("complete", ()=>{
// app code goes here if waiting for assets
var image = new Pic("image.png");
image.center();
S.update();
}); // end asset complete
// OR for multiple assets in an assets folder:
F.loadAssets(["sound.mp3", "spriteData.json", "spriteImage.png"], "assets/");
F.on("complete", ()=>{
// app code goes here if waiting for assets
const soundInstance = new Aud("sound.mp3").play(); // formerly asset("sound.mp3").play()
// later soundInstance.paused = true; // etc.
const sprite = new Sprite({json:"spriteData.json"});
sprite.center().run(2);
// the image for the sprite is specified in the JSON
// but we still want to load it so it is in the loadAssets()
// and the JSON data will take care of adding it to the sprite
S.update();
}); // end asset complete
} // end of ready
EXAMPLE
// lazy-load image - added in ZIM Cat
// this means that the asset is not passed into the Frame in the assets parameter
// and it is not added with loadAssets() but rather just called with asset().
new Frame(FIT, 1024, 768, dark, light, ready); // no assets parameter
function ready() {
// lazy-loading will make a container with type "AC" (Asset Container)
// it will store requested transform information
// such as that the container is supposed to be centered in this case
// (remember, the dimensions are unknown until the Bitmap is loaded)
// then call loadAssets() behind the scene
// and add the Bitmap to the container
// if loading is successful, it will rename the type to "Image"
// then it will use the dimensions to center the container
new Pic("image.jpg").center(); // formerly asset("image.jpg")
// there are many things that can be done to an object
// that need dimensions - ZIM tries to handle these
// but if there is something obscure like gesture bounds
// that ZIM may have missed then use conventional loading
// or try loading with dimensions provided:
new Pic("image.jpg", 100, 200).center();
// NOTE: do not lazy-load Sprite images.
}
EXAMPLE
// With multiple loadAsset() calls you can assign the results to a variable
// and use that variable for the events independently
// Warning, each of these will still call a frame complete event
// so usually you would use one or the other but not both
const first = F.loadAssets("image.png");
first.on("complete", ()=>{
const image = new Pic("image.png").center();
S.update();
});
const second = F.loadAssets("sound.mp3");
second.on("complete", ()=>{
const sound = new Aud("sound.mp3").play();
});
EXAMPLE
// if app is in an iFrame, this will get keyboardAccess using a hidden F.keyboardMessage()
// good for games that need keyboard if the game is in an iFrame like the Editor or CodePen
new Pane({content:"START", keyboardAccess:true}).show();
EXAMPLE
// dynamically adjusting touch - there are also touch and singleTouch parameters of Frame
// also, drag() has its own singleTouch parameter
const radio = new RadioButtons(30, ["MULTI TOUCH", "SINGLE TOUCH", "NO TOUCH"]).center().mov(0,-200).change(()=>{
if (radio.text.includes("MULTI")) F.singleTouch = false;
else if (radio.text.includes("SINGLE")) F.singleTouch = true;
else F.touch = false;
});
new Circle(50,white,red,5).center().mov(-100,50).drag();
new Circle(50,white,purple,5).center().mov(100,50).drag();
PARAMETERS supports DUO - parameters or single object with properties below
scaling - (default FULL) can have values as follows
Note: as of ZIM Cat 04, the constant FIT or the string "fit", etc. can be used
FIT sets canvas and stage to dimensions and scales to fit inside window size
FILL sets canvas and stage to dimensions and scales to fill window size (previously "outside")
FULL sets stage to window size with no scaling
"tagID" add canvas to HTML tag of ID - set to dimensions if provided - no scaling
FIT and FILL: width and height will set the stage width and height and the canvas is then scaled
this is handy because all your dimensions are set to start
FULL: width and height are ignored when scaling as these are set to the window width and height
TAG: if width and height are provided then the canvas and stage will be these dimensions
if width and height are not provided in tag mode, the canvas and stage will take the dimensions of the tag
this means, the tag must have some sort of width and height dimensions set or it will be really big!
In this mode, you may need to style the containing tag with CSS to get a desired effect.
width - (default 1024 except for full**) the width of the stage
height - (default 768 except for full**) the height of the stage
** if tag mode and no width or height then these will be the width and height of the tag
color - (default null) the background color of the frame (any CSS value) - or just set in styles
will be see-through if not specified
outerColor - (default null) the body color of the HTML page - null will not adjust the background color
ready - (default null) - an callback function for when the Frame is ready - rather than using the "ready" event
this will be passed frame specific (frame, stage, width, height, mobile) parameters
the stage is updated after this function is called
assets - (default null) - 1. a string asset or 2. an array of assets, 3. ZIM asset object, 4. ZIM multi-asset object
1. "logo.png"
2. ["logo.png", "bounce.mp3", "Reuben.otf"]
3. {id:"string", src:"logo.png", path:"assets/", loadTimeout:2, noCORSonImage:true}
4. [{assets:["one.png", "two.png"], path:"images/"}, {assets:["big.mp3", "oof.mp3"], path:"sounds/"}]
** see the loadAssets() method for details - including more file types, etc.
NOTE: "complete", "progress" and "fileLoaded" events are not dispatched
use loadAssets() for these if desired
the "ready" event will be dispatched when the canvas is ready and initial assets are loaded
NOTE: the loadAssets() method can still be used as desired
NOTE: as of ZIM Cat 04, SVG will be automatically converted to a Bitmap with and svg property of the original SVG.
SEE: https://zimjs.com/assetlist/ for many files
path - (default null) - a string path for the assets
if an assets object is provide with a path then this parameter is ignored
this will also set the ZIM PATH global to the path
ZIM PATH is used with lazy-loaded images (eg. when not using Frame assets parameter or loadAssets() method)
ticker - (default null) - an optional callback function to be added to the ZIM Ticker - rather than using Ticker.add();
this will be passed frame specific (count, frame, stage, width, height) parameters
count starts at 1 and the stage is updated after this function is called
also see the pauseTicker() method
progress - (default null) - set to a Waiter() or ProgressBar() object to show while loading
rollover - (default true or false on mobile) activates rollovers
touch - (default true) activates touch on mobile - this will be multitouch by default
set to false for no touch on mobile
also see singleTouch parameter to set singleTouch
also see touch and singleTouch properties
scrollTop - (default false) activates scrolling on older apple devices to hide the url bar
align - (default CENTER) for FIT and FILL, the horizontal alignment LEFT, CENTER, RIGHT
valign - (default CENTER) for FIT and FILL, the vertical alignment TOP, CENTER, BOTTOM
canvasID - (default "myCanvas" or if subsequent frame, myCanvas+randomID) will be set to tagIDCanvas if a tagID is provided - eg. scaling="test", canvasID="testCanvas"
rollPerSecond - (default 20) times per second rollover is activated (if rollover parameter is true)
delay - (default .03 and 1 for mobile) seconds to resize at load and after orientation change (also see ZIM TIME constant)
some devices are slow to report true width and height
At loading, mobile will be tested right away and then at .1 seconds
the default is to then test again at the delay (default 1 second)
At resize, mobile will be tested every .05 seconds up to the delay
set this to some other time if desired
if set to 0 then no additional test will be done - not even the one at .03 seconds
canvasCheck - (default true) check to see if there is canvas support - uses !!window.HTMLCanvasElement
gpu - (default false) set to true to use a CreateJS StageGL stage for GPU renderer
note: retina will be turned off if gpu is on otherwise antialiasing really looks bad
See: https://blog.createjs.com/stagegl-faster-better-stronger-webgl-update-easeljs/ (written before version 1 release)
gpuObj - (default null) object with following properties (with defaults) See CreateJS docs on GITHUB:
preserveBuffer (false), antialias (false), transparent (false), premultiply (false), autoPurge (1200)
nextFrame - (default null) set to zim Frame object of Frame underneath current Frame to pass events to nextFrame
nextStage - (default null) alternative to nextFrame if the stage beneath current Frame is not a ZIM Frame but just a CreateJS Stage
allowDefault - (default false - true for tag mode) set to true to allow default mouse, key and scrollwheel events on canvas
See also the zil property of frame that allows you to add and remove these events dynamically (except for mouse swipe scroll and zoom on mobile)
allowDefault of false also sets body overflow to hidden - which is good for full, fit and fill modes
also see allowDefault property
loadFailObj - (default result of F.makeCircles) object that shows if asset() does not exist or did not load withing loadTimeout
This will be given a type property of "EmptyAsset"
Set the loadFailObj property below to null to set no object - but this will yield errors unless each resulting asset() is tested
Set to new Container() to show nothing (but avoid errors) - or new Rectangle(10, 10) to show little black square, etc.
sensors - (default false) set to true to capture Frame devicemotion and deviceorientation events - see Events
retina - (default true) scales stage to use pixelDensity (sharper when scaling up) and supports Adobe Animate export
may need to set mouse event targets to e.stageX/zim.scaX and e.stageY.zim.scaY
except for using S.getObjectUnderPoint()
ZIM overrides CreateJS localToGlobal, globalToLocal and localToLocal to accomodate stage scaling
This was a major adjustment to transform(), bezier controls, outline, physics, etc.
set to false to return to traditional PRE ZIM 10.3.0 unscaled stage
mouseMoveOutside - (default false) set to true to capture mouse movement outside the stage
see also mouseX and mouseY properties of frame - these work with ZIM retina without adjusting for stage scale
captureMouse - (default true) set to false to not use stagemousemove event to set F.mouseX and F.mouseY (good with Retina)
shim - (default null) used by ZIM SHIM 2 https://zimjs.com/animate/ to create Frame with pre-existing stage and canvas
accepts an object with stage and canvas properties - lets Adobe handle resize
maxConnections - (default 10) set the maximum number of concurrent connections.
From CreateJS PreloadJS: Note that browsers and servers may have a built-in maximum number of open connections,
so any additional connections may remain in a pending state until the browser opens the connection.
maxNum - for sound this is how many instances of the sound can play at once
also can set in asset object maxNum property and loadAssets() and asset() maxNum parameters.
also see sound interrupt parameter
singleTouch - set to true for single touch rather than the default multitouch (or touch false)
this will override the touch setting to turn touch to true
also see touch and singleTouch properties
METHODS
loadAssets(assets, path, progress, xhr, time, loadTimeout, outputAudioSprite, crossOrigin, fileType, queueOnly, maxConnections, maxNum) |ZIM DUO| also accepts ZIM DUO configuration object as single parameter
// see also assets and path parameters of Frame - which share the info below
// see https://zimjs.com/assetlist/ to get an array of many files
assets - a file (url String, asset object or multi-asset object) or files in an Array
each asset String is how you then access the asset with the asset() method of Frame
asset types (from CreateJS PreloadJS): Image, Font, JSON, Sound, SVG, Text, XML
NOTE: as of ZIM ZIM 02, fonts can be loaded with just the font file name (including Google Fonts) rather than a ZIM font object - see FONTS in the Docs.
NOTE: as of ZIM Cat 04, SVG will be automatically converted to a Bitmap with and svg property of the original SVG.
asset can also be a ZIM asset object:
{id:"string", src:"filename", path:"dir/", loadTimeout:1, maxNum:num, noCORSonImage:true}
then can use the id to access the asset in the asset() method of Frame
filename will be added to an overall path if a path parameter is provided
or overwritten with a local path if a path property is provided
an asset object with a filename of an absolute filename starting with http will ignore path
loadTimeout (default 8) will override the loadAssets() loadTimeout
this is how many seconds to wait for asset before error and a complete fires even though asset not loaded
maxNum (browser default) is used with sound to specify the maximum number of sounds of the same source to play at one time
this can be used with the interrupt parameter of the play() method
to ignore multiple sounds or start the sound over again instead of playing multiple versions
noCORSonImage (default false) set to true to make an HTML img tag and read it into a ZIM Bitmap to avoid CORS testing
it then uses ZIM expand(0) to add a CreateJS hitArea to the Bitmap allowing it to be interactive and avoid CORS
thanks Disco for the technique
note: this means the Bitmap will be interactive everywhere - not just in opaque areas
note: loading images this way will not count as progress (bytes loaded ratio) in the progress event but do count for fileloaded and complete events
asset can be a ZIM multi-asset object {assets:[], path:"dir/", loadTimeout:1, maxNum:num, noCORSonImage:true}
where the array can hold multiple files that will have the provided properties applied
this is handy for loading assets from multiple directories (added in ZIM Cat 02 - thanks Netanela for the prompting)
eg.
[
{assets:["one.png", "two.png"], path:"images/"},
{assets:["big.mp3", "oof.mp3"], path:"sounds/"}
]
** warning - if an asset has the same name as a previous asset, then the later asset id will have the path added to its id
** for example:
[
{assets:["one.png", "two.png"], path:"images/"},
{assets:["one.png", "man.png"], path:"portraits/"}
]
** then asset("one.png") will be the asset in the images folder
** and asset("portraits/one.png") will be the asset in the portraits folder
asset can also be a font object - but as of ZIM ZIM 02, fonts can be loaded with just the file name, including Google Fonts
DO NOT use uppercase letters on mobile apps
{font:name, src:url, type:string, weight:string, style:string} // with last three properties being optional
eg.
{font: "wildwood", src:"ChurchintheWildwood-Regular.ttf", type:"OpenType"} // type is not needed
{font: "regu", src:"regul-bold.woff", weight:"bold"}
{src:"https://fonts.googleapis.com/css?family=Roboto"}
For google fonts https://fonts.google.com/ you add extra information to the url so the font (family), type, weight and style are ignored
If absolute src is used, path parameter is ignored - otherwise path is added to start of src
After loading, can just use:
var label = new Label("hello", 30, "wildwood") // or whatever the font property is
asset can be an AudioSprite - which is a single sound file and data for sounds within the sound file:
ZIM has a format for the data and so does CreateJS - there is also the parseAudioSprite() method for importing formats
See the parseAudioSound parameter to pre-parse the ZIM format then use the resulting CreateJS format to avoid live parsing (maybe save a millisecond)
ZIM FORMAT:
{src:"audiosprite.mp3", audioSprite:[
// [id, startime(s), endtime(s)]
// prefer this when making audioSprites by hand in Premiere or Audition
['blackball', 1.041, 2.475],
['bounce', 3.567, 4.232]
]}
CREATEJS FORMAT:
{src: "audiosprite.mp3", data:{ // extra data property
audioSprite: [
{id:"sound1", startTime:0, duration:500}, // time in ms
{id:"sound2", startTime:1000, duration:400},
{id:"sound3", startTime:1700, duration: 1000}
]
}}
See also previewAudioSprite() method in the META section of docs.
path - pass in an optional path String that gets prepended to the asset
when accessing the asset with the asset() method you do NOT include the path
assets with an absolute URL (http[s]://etc.) will ignore path
this will also set the ZIM PATH global to the path
ZIM PATH is used with lazy-loaded images (eg. when not using Frame assets parameter or loadAssets() method)
progress - (default null) - set to a Waiter() or ProgressBar() object to show while loading
xhr (default true) the loading method for files - perhaps will need to set to false in some cases (WEBP alternative from Cloudflare, etc.)
time (default 0) is the minimum number of seconds for the complete event to trigger
use this for testing or to always have time to show a loading message
loadTimeout (default 8) is how many seconds to wait for asset before error and a complete fires even though asset not loaded
outputAudioSprite (default false) set to true when passing in a ZIM AudioSprite format to output to the console a CreateJS AudioSprite JSON object
JSON.parse() this object before passing in to loadAssets() - and add single quotes around console output as those are stripped by console
crossOrigin (default "anonymous") - leave at default to load from Amazon S3, etc.
had to add <AllowedMethod>HEAD</AllowedMethod> in CORSRule of CORS configuration on Amazon S3 for fonts
https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html#how-do-i-enable-cors
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-cors
and had to edit distribution behaviours for cache header > whitelist and move over Origin
NOTE: this will still not get past CORS if there is no CORS provided
see noCORSonImage property of ZIM asset object for an image solution to bypass CORS
fileType (default null) in cases where the file type cannot be parsed or is parsed incorrectly, this overrides
might have to split up loading as this fileType gets applied to all files loaded
Types are for CreateJS PreloadJS: https://www.createjs.com/docs/preloadjs/classes/LoadQueue.html
createjs.Types.BINARY: Raw binary data via XHR
createjs.Types.CSS: CSS files
createjs.Types.IMAGE: Common image formats
createjs.Types.JAVASCRIPT: JavaScript files
createjs.Types.JSON: JSON data
createjs.Types.JSONP: JSON files cross-domain
createjs.Types.MANIFEST: A list of files to load in JSON format, see AbstractLoader/loadManifest
createjs.Types.SOUND: Audio file formats
createjs.Types.SPRITESHEET: JSON SpriteSheet definitions. This will also load sub-images, and provide a SpriteSheet instance.
createjs.Types.SVG: SVG files
createjs.Types.TEXT: Text files - XHR only
createjs.Types.VIDEO: Video objects
createjs.Types.XML: XML data
queueOnly (default false) - set to true to send events only to the Queue object (see below) rather than the Frame
when using queues to accept events, remember that the frame also receives events
if you also have some general frame events for loading, set this parameter to true to avoid accident
maxConnections - (default the Frame maxConnections) set the maximum number of concurrent connections.
From CreateJS PreloadJS: Note that browsers and servers may have a built-in maximum number of open connections,
so any additional connections may remain in a pending state until the browser opens the connection.
maxNum - for sound this is how many instances of the sound can play at once
also see sound play() interrupt parameter
RETURNS: a Queue object that can be used for control with multiple loadAssets calls
Each Queue will trigger progress, assetload and complete events
Each Queue will have a preload property to the CreateJS LoadQueue and an isLoading property
The frame also has these events and properties but acts for all loading - so be careful - see the queueOnly parameter
It is recommended to use the Queue any time you use multiple LoadAssets() calls at the same time
You still access assets with asset() as outlined below whether you use the Queue or not
asset(file, width, height, maxNum) - access an asset such as an image or sound - see loadAssets() for more on types
note: asset() is a general alternative to new Pic(), new Aud(), new Dat() - also see new Vid() and new SVG()
file is the string name or url to the file
if the asset was loaded with a string then use the string (less the path if provided)
if the asset was loaded with a full URL then use the full URL here
if the asset uses an asset object with an id then use the id
file can be a |ZIM VEE| value so for instance, an array and asset will pick randomly - or a series, etc.
** warning, if the assets are loaded with ZIM Multi-asset Objects with assets and path
** and an asset has the same name as a previous asset, then the later asset id will have the path added to its id
width and height will help the auto-loading (lazy-loading) otherwise, ZIM will recall positioning applied before the asset is loaded
** otherwise there is no need to add a width and height - only do so to optionally help auto-loading
maxNum - for sound this is how many instances of the sound can play at once - also see sound play() interrupt parameter
** asset() is available as a global function asset() or if zns (ZIM name space) is true then as zim.asset()
** if there are two or more frames, then use F.asset() not asset()
** traditionally, these have been preloaded into the Frame asset parameter or with Frame loadAssets()
** As of ZIM Cat, using asset() without preloading will automatically load the asset - thanks Ami Hanya for suggestion
this works only for images and sound and should be used sparingly as each asset has its own preloading
and some things like sprite assets may have issues.
** As of ZIM ZIM, there is a ZIM PATH constant that can be used to set the path for automatic loading (lazy-loading)
see the docs under ZIM PATH for details
** asset() will add "complete" and "assetLoad" event to the asset object
if the asset is an image then this is a Bitmap which can be added to the stage, etc.
if the asset is a sound then use asset(file).play();
play has ZIM DUO params of volume, loop, loopCount, pan, offset, delay, interrupt
see the ZIM Docs on Sound (below the Frame) for param information
if the asset is anything else, then it is what it is!
asset() will have a type property depending on what type (except JSON, XML and text which are just the object itself)
for instance, an image will have type "Bitmap" as it is a ZIM Bitmap object
but a lazy-loaded image will have type "Image" as it is actually a Container holding a Bitmap
and its Bitmap can be accessed with the bitmap property - so asset("auto.png").bitmap will access the Bitmap
a lazy-loaded sound will have type "Sound"
asset.getIDs() will return an array of asset IDs.
zim.assets is an object literal that holds all the assets based on ID
consider this to be read only
this is the object that the asset() function calls so usually just use asset()
object(name) - get a DisplayObject (for example a Circle or Button) by its name.
** object() is available as a global function object() or if zns (ZIM name space) is true then as zim.object()
DisplayObjects do not start with a name but can be named if desired. Usually, we use variable names to reference an object
See the DisplayObject name property and the nam() short chainable method to set a name
object.getNames() will return an array of object names that have been set.
any object that is named the same name as another object will overwrite the other object and will not be in the object() list anymore
follow(obj, boundary, damp, dampY, leftOffset, rightOffset, upOffset, downOffset, offsetDamp, offsetDampY, horizontal, vertical, borderLock, lag) |ZIM DUO|
moves obj container to keep provided object in middle of stage view
pass in null for obj to stop following
See https://zimjs.com/ten/follow.html - with keys
See https://codepen.io/danzen/pen/gNKQYY - with press
** supports DUO - parameters or single object with properties below
obj - the Display Object to follow - works well if controlling obj with ZIM Motion Controller (mousedown, keydown, gamebutton, gamestick)
unlike Physics follow() the obj for Frame follow() must be in a container - the container will be moved
boundary - (default stage size) - or use a ZIM Boundary() object to specify x, y, width and height to keep obj inside
see also followBoundary property of Frame to update this boundary in a frame "resize" event function when frame is in "full" scaling mode
damp - (default .05) the damping of the motion - 1 moves faster, 0 not at all
dampY - (default damp) can set to damp vertical movement at a separate rate
leftOffset - (default 0 from left of boundary)
rightOffset - (default 0 from right of boundary) - differs from Physics follow which is distance from 0 to right offset
the object will try and move to leftOffset when moving right and rightOffset when moving left
this counters the damping so that the user can see in the direction of motion
when the object is not being controled it moves to the average between left and right offsets
upOffSet - (default 0 from top of boundary)
downOffSet - (default 0 from bottom of boundary)
same as offsets above but in the y direction
offsetDamp - (default .02) the damping for moving the object to the offset
offsetDampY - (default offsetDamp) - damping for moving the object to the y offset if desired to be different than x
horizontal - (default true) set to false to not follow horizontally
vertical - (default true) set to false to not follow vertically
borderLock - (default false) set to true to stop container at boundary
lag - (default false) set to true to position object back from direction of motion
this gives more view as moving but sort of goes in two directions when motion stops
setDefault() - sets the frame to be the default frame
by default ;=) the default frame is the first frame made
the default frame has the stage that addTo(), center(), etc. will use as the default container
a global varible called zdf is also available
as of ZIM ZIM 01, global variables F, S, W, H are provided for frame, stage, width and height of the default frame
keyboardMessage(color, backgroundColor, message, response, percent, call) |ZIM DUO| - place a message to press screen for keyboard control
works with iFrames as well to avoid having to press outside the canvas on the iframe
it does this by turning off the canvas pointer events until the iframe is pressed
color defaults to yellow, backgroundColor to black
response is the message given when the stage or iframe has been pressed to activate the keyboard
pass in "" for no message and response - to use a custom Pane() for example.
percent defaults to 80% the stage width
call - the function to call when keyboard is active - or see keyboardactive event
returns the label if repositioning is desired
Dispatches a "keyboardactive" event when pressed to activate keyboard
fullscreen(mode) - set Frame to HTML fullscreen - mode defaults to true - set to false to come out of fullscreen
also see isFullscreen property and two fullscreen events
note: this is nothing to do with "full" scaling mode but rather the Browser window F11 fullscreen
see: https://zimjs.com/expand to go from ZIM "tag" scaling mode to ZIM "fit" scaling mode
makeCat(height) - returns a ZIM Cat icon - provide height rather than scaling for better caching if cached
if mobile, the icon will be cached - can uncache() it if desired
makeIcon(edges, box, slats, borderColor, borderWidth) |ZIM DUO| - returns a ZIM Z icon
edges defaults to zim.light and is the top and bottom line in the Z
box defaults to zim.dark and is the background box color
slats defaults to the ZIM colors but can be set to any array of five colors (setting true will set to zim.silver)
borderColor and borderWidth default to null - or borderWidth 1 if color set and borderColor black if borderWidth set
madeWith(color, text, edges, box, slats, borderColor, borderWidth) |ZIM DUO| - returns a ZIM Z icon with Made With message
color - (default zim.dark) change color of text (pass in clear to hide text)
text - (default: "Made with ZIM") change to desired made with message
other parameters see makeIcon() above
makeCircles(radius, multiple) - returns ZIM Circles (centered reg)
radius defaults to 100
multiple defaults to false which will return a ZIM Shape - set to true to return a ZIM Container of ZIM Circles
remakeCanvas(width, height) - removes old canvas and makes a new one and a new stage
will have to set your local stage, W and H variables again
update() - call this if frame position is moved on the HTML page
for instance, when a div to left has its display style set to none and the frame shifts over
calling update() will dispatch an update event to any TextArea, Loader or Tag objects
so they resize properly with the new F.x and F.y values
dispose() - removes canvas, resize listener and stage
PROPERTIES
type - holds the class name as a String
stage - read only reference to the zim Stage - to change run remakeCanvas()
frame gives the stage read only S.width and S.height properties
frame gives the stage a frame property that points to the frame that made the stage
canvas - a reference to the frame's canvas tag
canvasID - a reference to the frame's canvas ID
color - the color of the frame background - any css color
outerColor - the color of the body of the HTML page - set with styles
scaling - holds the scaling mode - FULL, FIT, FILL (or "full", "fit", "fill"), "tag" or "inline"
tag is tag mode with no dimensions and inline is tag mode with dimensions
also see the tag property below if mode is tag or inline
tag - the containing tag if scaling is set to an HTML tag id (else null)
isDefault - a Boolean to indicate whether the Frame is the default frame (see setDefault() method)
the default frame has the stage that addTo(), center(), etc. will use as the default container
a global varible called zdf is also available
isLoading - a Boolean to indicate whether loadAssets() is currently loading assets (also, each queue has an isLoading property)
isFullscreen - a Boolean to indicate if Frame is in HTML fullscreen mode - see fullscreen() method and events
width - read only reference to the stage width - to change run remakeCanvas()
height - read only reference to the stage height - to change run remakeCanvas()
scale - read only returns the scale of the canvas - will return 1 for full and tag scale modes
mouseX, mouseY - read only value of the mouse x and y positions on the canvas
note: the frame captureMouse parameter must be set to true (default)
note: this value includes the division by the stage scale needed for ZIM Retina
whereas getting the mouse coordinates from a mouse event object does not include division by the stage scale
set frame's mouseMoveOutside parameter to true to capture movement outside the canvas
cursors - get or set an object literal with custom cursors to override the CSS cursors or act on their own
See: https://zimjs.com/014/cursors.html
the format is:
F.cursors = {default:DisplayObject, pointer:DisplayObject, madeUp:DisplayObject, etc.}
NOTE: use the cur() method to set cursors - DO NOT use the cursor property to set cursors
drag(), tap(), etc. will already work with the custom cursor system
set F.cursors = null to turn off custom cursors
cursorsExclude - object or [objects] not to get custom cursors
NOTE: the cur() must be set on the object for the exclude to work
if the cur() is set on an object inside a container then the exclude must be set manually (after F.cursor is set)
innerObject.cursor = "default"; // or "pointer", etc.
innerObject._cursor = null; // clear custom cursor flag
cursorObj - the current custom cursor object
cursorList - a Dictionary that holds data for cursors - used internally to keep track of custom cursors
cursorTypes - an array of valid CSS cursors - used internally to watch for invalid CSS cursors if name used is not in cursors
leftMouseDown - read only value as to whether the left mouse button is down
used internally by drag and others to make sure pressup on iFrames is handled when the mouse comes back on the stage
also see "mouseupplus" event
mousedownEvent - a reference to the frame "stagemousedown" event - can set F.off("stagemousedown", F.mousedownEvent)
mousemoveEvent - a reference to the frame "stagemousemove" event - can set F.off("stagemousemove", F.mousemoveEvent)
orientation - VERTICAL or HORIZONTAL (updated live with orientation change)
visibleLeft, visibleTop, visibleRight, visibleBottom - in "fill" scale mode these give window edge locations relative to the stage
can be used to position items like navigation relative to window as the frame resize event is fired
in all scale modes other than "fill", the values are 0, W, 0, H
zil - reference to zil events that stop canvas from shifting or scrolling - also see allowDefault parameter
can set allowDefault property to false then allow specific defaults by removing zil events - see zil global function
example: window.removeEventListener("keydown", F.zil[0]); removes keydown preventions (for page up, page down, home, end, etc)
allowDefault - set to true to remove zil or false to set zil (see above) also affects body overflow
touch - get or set the touch setting - setting to false will not allow touch on mobile
also see touch and singleTouch parameters and singleTouch property
singleTouch - get or set the singleTouch setting - set to true to turn on single touch and false to turn on multitouch
setting either true or false will set the touch property to true
also see the touch and singleTouch parameters and touch property
followBoundary - update with a ZIM Boundary for follow() if "full" mode Frame "resize" event happens, etc.
altKey - true if the alt key is being pressed otherwise false
ctrlKey - true if the ctrl key is being pressed otherwise false
metaKey - true if the meta key (⌘ command on Mac or ⊞ windows key) is being pressed otherwise false
shiftKey - true if the shift key is being pressed otherwise false
loadFailObj - the object that shows if images are broken - will be given a type property of "EmptyAsset"
startTime - datestamp of when frame was made - used internally
retina - read-only Boolean as to whether stage (as opposed to the canvas) was scaled for pixelDensity during Frame creation
reloaded - read-only Boolean as to whether page has been reloaded - uses window.performance.getEntriesByType
ALSO see F, S, W, H, M global variables which reference the default frame, its stage and width and height, and if on mobile
EVENTS
"ready" - fired when the stage is made (and state update will be called after dispatched) - also see ready parameter
"failed" - fired if no canvas support (and canvasCheck parameter is set to true - which is the default)
"resize" - fired on resize of screen
"update" - fired when F.update() is called - read by Loader, TextArea and Tag objects
note: this is for when the frame is moved within an html page
for instance, when a div to the left has its display set to none - then call F.update();
"orientation" - fired on orientation change
"contextmenu" - fired on right click
to prevent the default right click then use
e.preventDefault() in your event function.
see https://zimjs.com/explore/contextmenu.html
"keydown" - fired on keydown - just like the window keydown event with eventObject.keyCode, etc.
also stores F.altKey, F.ctrlKey, F.metaKey, F.shiftKey
Note: Alt ArrowLeft and Alt ArrowRight has been set to go back or forward in the browser history
"keyup" - fired on keyup - just like the window keyup event with eventObject.keyCode, etc.
"pointerdown", "pointermove", "pointerup", "pointerenter", "pointerleave" - mirrors DOM Pointer Events
Note: the event object is a raw JavaScript event object, not a CreateJS event object
so there is no clear() on the event object nor a once parameter for the on() method, instead use:
const ev = F.on("pointerdown", ()=>{
F.off("pointerdown", ev);
// this will only run once
});
"mouseupplus" - fired when the browser window receives a mouseup event
NOTE: deprecated - would suggest using pointerup instead of this
also fired when the mouse enters the stage from an iFrame and is no longer down.
Note there is no eventObject.
ALSO see mouseupplusonly for only firing as mouse enters the stage from an iFrame and is no longer down.
mouseup, pressup, stagemouseup, etc. do not work when the mouse is up over an iframe or outside an iframe
ZIM drag() makes use of this event to stop the drag if the mouse was up over an iframe or outside the an iframe holding the canvas.
This could have been done with setting events on parent windows but this runs into CORS errors in many cases
This event fires on the bubbling phase so can be ignored if a real press up is in place - for instance:
record a check variable as true when mousedown and false when pressup which also calls an up function.
In a mouseupplus event function, activate the up function only if the check variable is still true.
This will call the up function as the mouse comes back onto the stage
if the mouse was down when leaving the stage and let up outside the iframe the canvas is in - goodness.
"mouseuplusonly" - fired when the mouse comes back from an iframe (not holding the canvas)
NOTE: deprecated - would suggest using pointerup instead of this
and the mouse was down on the canvas and up in the iframe.
this does not fire on a regular mouseup whereas the mouseupplus will.
"wheel" - fired on mousewheel (Window wheel event)
can get eventObject.deltaX and eventObject.deltaY
these vary greatly in value based on Browser
may want to just ask for sign(eventObject.deltaY) and multiply it by a factor
and then perhaps constrain the value - here the scale is constrained between .5 and 5
note - when changing scale, it is better to multiply by a factor rather than add to the scale
eg. circle.scale = constrain(circle.scale*(sign(e.deltaY)>0?.75:1.25), .5, 5);
"deviceorientation" - turned on when using ZIM PermissionAsk()
fired as device orientation changes:
eventObject.rotation.x (beta in HTML specs) holds rotation about the x axis between -180 and 180 (tipped forward or backward)
eventObject.rotation.y (gamma in HTML specs) holds rotation about the y axis between -90 and 90 (tipped left or right)
eventObject.rotation.z (alpha in HTML specs) holds rotation about the z axis 0-360 clockwise (relative to orientation when app loads)
note rotation.z is 360-alpha compared to the HTML 5 specs
note also that beta, gamma and alpha from the HTML 5 specs are also provided
eg.
var label = new Label().center();
// Note: MUST USE PermissionAsk()
F.on("deviceorientation", function(e) {
label.text = e.rotation.x +","+ e.rotation.y +","+ e.rotation.z;
S.update();
});
"devicemotion" - turned on when using ZIM PermissionAsk()
fired on moving mobile device - like a tilt or shake - eventObject.acceleration holds x, y and z properties of motion
eg.
var label = new Label().center();
// Note: MUST USE PermissionAsk()
F.on("devicemotion", function(e) {
label.text = e.acceleration.x +","+ e.acceleration.y +","+ e.acceleration.z;
S.update();
});
"fullscreenenter" - dispatched going into fullscreen - see fullscreen() method
"fullscreenexit" - dispatched if coming out of fullscreen - see fullscreen(false) method
"tabfocus" - dispatched when tab gains focus - only dispatched by the zdf (ZIM Default Frame)
ZIM setBlurDetect() is now activated by Frame and used by ZIM in animate(), timeout(), interval(), wiggle()
"tabblur" - dispatched when tab loses focus - only dispatched by the zdf (ZIM Default Frame)
"keyboardactive" - dispatched if keyboardMessage() is called and keyboard is active
ASSET EVENTS
loadAssets() will trigger these events on the Frame object and on the specific queue (eg. var queue = F.loadAssets();)
NOTE: if loadAssets() queueOnly parameter is true, then only the queue receives the events - see queueOnly parameter
"progress" - fires constantly as assets are loaded with loadAssets() to represent overall load progress (fonts not included)
The event object has a progress property between 0 and 1
"assetload" - fired when an asset loaded with loadAssets() or asset() has loaded (use asset property of event object to get its file and src) (fonts not included)
"complete" - fired when all assets loaded with loadAssets() or asset() are loaded
"error" - fired when there is a problem loading an asset with loadAssets()
If the assets are loaded in the Frame then the error event must be captured outside the ready event
and if loadAssets() or lazy-load with asset() are used then the error event must be captured outside the complete event
MORE: http://zimjs.com/code/bits.html?title=Frame
************************************
[89124] Pic(file, width, height, noCors, style, group, inherit)
Pic
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Use Pic() to show an image, such as a jpg, png, webp, etc.
There may be a security error when loading images locally for any Canvas app.
Please read https://zimjs.com/tips.html#IMAGES for easy solutions.
Before ZIM version ZIM 00, asset() or F.asset() was used to show images.
These can still be used if desired. The Pic() class just wraps the asset() call.
SEE: https://zimjs.com/zim/assets.html
PRELOADING
It is recommended that you preload images (along with sounds, etc.) using the Frame() assets and path parameters.
Batch l