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#FRAMEhttps://zimjs.com/tips#IMAGEShttps://zimjs.com/tips#SOUNDhttps://zimjs.com/tips#FULLSCREENNOTE
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();
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
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
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-corshttps://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
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
colors: orange, green, pink, blue, brown, yellow, red, purple, silver, tin, grey, lighter, moon, light, dark, darker, white, black, clear (0 alpha), faint (.01 alpha)
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.
"mouseupplus" - fired when the browser window receives a mouseup event
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)
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" - MUST SET Frame sensors parameter to true
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();
F.on("deviceorientation", function(e) {
label.text = e.rotation.x +","+ e.rotation.y +","+ e.rotation.z;
S.update();
});
"devicemotion" - MUST SET Frame sensors parameter to true
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();
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
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
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 loading images is more efficient and the width and height will be available when the Frame() is "ready" or loadAssets() is "complete".
Images can also be loaded on demand with F.loadAssets() at any time - for instance, for a second section of the app.
LAZY-LOADING
If images are not preloaded then Pic() will use automatic loading (lazy-loading).
If width and height are provided, all will go smoothly.
If width and height are not provided, ZIM will store various scaling and positioning commands
and re-apply the commands once the images are loaded.
This happens for center(), centerReg(), pos(), scaleTo(), outline() and perhaps others.
This extra work is NOT required if assets are preloaded or a width and height are provided.
Some controls like Tile() and Scroller() must have dimensions and will give a warning in the console.
In the past there has been issues with cloning lazy-loaded images before they are loaded, but this should work now.
Pic will give a "ready" and a "complete" event when loaded.
These events are triggered 20 ms after making the object if the object is already preloaded.
NOTE
Pic is a container with a bitmap inside (see bitmap property).
This means that other objects can be added to the Pic object.
This is like the ZIM Shapes (Rectangle, Circle, etc.) which are containers and can have objects added to them.
If doing this, note that the container has its mouseChildren turned off
so when dragging, for instance, the whole pic moves rather than the bitmap inside the pic.
To interact with objects inside, set pic.mouseChildren = true.
Generally, for clarity, avoid adding objects to Shapes or Pics unless you are used to the mouseChildren setting.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// lazy-load an image in the same directory
new Pic("image.png").center();
// NOTE: the above may give a CORS security error locally
// to easily solve this see https://zimjs.com/tips.html#IMAGES
EXAMPLE
// lazy-load an image in the assets/ directory
new Pic("assets/image.png").center();
EXAMPLE
// lazy-load an image in the assets/ directory using PATH constant
PATH = "assets/"
new Pic("image.png").center();
EXAMPLE
// preload the image in the Frame along with path parameter
new Frame(FIT, 1024, 768, light, grey, ready, "image.png", "assets/");
function ready() {
new Pic("image.png").center(); // adds the preloaded assets/image.png
// the PATH would be set to "assets/" by the Frame path parameter
new Pic("sky.png").addTo(); // would lazy-load assets/sky.png
PATH = "people/";
new Pic("laura.png").addTo(); // would lazy-load people/laura.png
new Pic("peter.png").addTo(); // would lazy-load people/peter.png
}
EXAMPLE
// preload all the images above
// the first two will use the path parameter
// the other two are in a different directory so can use an assets object {} with a different path
const assets = ["image.png", "sky.png", {assets:["laura.png", "peter.png"], path:"people/"}];
const path = "assets/";
new Frame(FIT, 1024, 768, light, grey, ready, assets, path);
function ready() {
new Pic("image.png").center(); // adds the preloaded assets/image.png
new Pic("sky.png").addTo(); // adds the preloaded assets/sky.png
new Pic("laura.png").addTo(); // adds the preloaded people/laura.png
new Pic("peter.png").addTo(); // adds the preloaded people/peter.png
}
// alternatively the path could have been added to each asset:
assets = ["assets/image.png", "assets/sky.png", "people/laura.png", "people/peter.png"];
// this would be passed into Frame along with no path parameter
// and the assets would then be accessed in the ready event with the path included:
new Pic("asset/image.png").center();
EXAMPLE
const plates = ["plate1.png", "plate2.png", "plate3.png"];
// lazy-load random plate pictures in a Tile
// below would be broken with a warning in the console
// because the tile does not know the plate dimensions
new Tile(new Pic(plates), 4, 4).center();
// below would work because the dimensions of 200, 200 were provided
// however, if the plates are not actually 200,200 then it may look wrong
new Tile(new Pic(plates, 200, 200), 4, 4).center();
// below would work because preloading in Frame() or loadAssets() provides real dimensions
// when the tile is made, the dimensions are known
const load = F.loadAssets(plates);
load.on("complete", ()=>{
new Tile(new Pic(plates), 4, 4).center();
S.update();
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
file - |ZIM VEE| the String file name of the image including file extension for instance, "pic.png"
There is a global PATH constant that can be set to add a path to the start of the file name
for instance setting PATH = "assets/" would then look for "assets/pic.png".
If a path is provided to Frame() parameter or the loadAssets() then these will automatically set the global PATH constant.
width - (default null) optionally predict the width of the image
The width will be ignored and the actual width will be used if the image is preloaded
and if lazy-loaded, the width will be replaced with the actual width after the image is loaded.
So the width is only used to tell something like a Tile(), what size to expect before the image is loaded.
To change the width of a Pic, use siz() or sca() methods
or width, widthOnly, height, heightOnly, scale, scaleX and scaleY properties.
height - (default null) optionally predict the height of the image (see width for similar details)
noCors - (default false) set to true to attempt to bypass CORS (cross origin resource sharing) issues.
CORS errors may show up when loading images from other servers that do not have settings saying this is allowed.
Setting noCors to true will try and load the image with a proxy server https://cors.zimjs.com/ so use sparingly.
It is better to try and load the images from your own server or get CORS permissions from the server.
Do not preload the image with this setting - or preload using an asset object with noCORSonImage:true set.
The noCors setting will use image() rather than asset()
All these solutions use https://cors.zimjs.com/https://theurltotheasset.jpg
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
keyOut(color, tolerance, replacement) - remove a certain color in the picture and make it see-through - with a color tolerance between 0-1
the default color is "#389b26" which is a medium dark green
the default tolerance is .1 - the higher the tolerance the less sensitive the keying process - so more colors will be removed similar to the provided color
color and tolerance can be an array of colors and tolerances (or just one tolerance if all are the same)
replacement (default clear) a color to replace the keyed out color with or an optional array to match the colors array if an array is used
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
in this case the type is "Pic" but if the Pic is lazy-loaded then
it starts as type "AC" (Asset Container) if no dimensions are provided
or "ACWD" (Asset Container With Dimensions) until the image is loaded
at which point, the type is set to "Pic"
bitmap - reference the the ZIM Bitmap (picture) inside the Pic container
file - the filename used
src - the source with path and filename - available on complete event
image - the HTML image tag - available on complete event
item - the CreateJS data item used for preload - available on complete event
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "complete" and a "ready" event (use either one) when the image is loaded
if preloaded this is dispatched 20 ms after the Pic is made
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
Aud
zim class - extends a createjs.EventDispatcher
DESCRIPTION
Use Aud() to play a sound with its play() method.
The app must be interacted with before a sound can be played.
There may be a security error when loading sounds locally for any Canvas app.
Please read https://zimjs.com/tips.html#SOUND for easy solutions.
Multiple instances of a sound can be played from the same Aud() object.
When a sound is played it returns an object that can be used to change that specific instance.
Use that object to change the volume, pan, to find out if the sound has looped or is complete
or to pause() or stop() the sound.
Before ZIM version ZIM 00, asset() or F.asset() was used to play sounds.
These can still be used if desired. The Aud() class just wraps the asset() call.
SEE: https://zimjs.com/zim/assets.html
PRELOADING
It is recommended that you preload sounds (along with images, etc.) using the Frame() assets and path parameters.
After the frame loads, sounds can also be loaded on demand with F.loadAssets().
Batch loading sounds is more efficient and the sound will be ready when the Frame() is "ready" or loadAssets() is "complete".
LAZY-LOADING
If sounds are not preloaded then Aud() will use automatic loading (lazy-loading).
Aud will give a "ready" event when loaded.
This event is triggered 20 ms after making the object if the object is already preloaded.
The "complete" event is used for when the sound is finished playing (not finished loading).
AUDIOSPRITE
An AudioSprite can alternatively be used which has many sounds in one sound file.
There is data that goes with the AudioSprite to match a label to a time and duration.
See the Frame docs under loadAssets() method although they can be loaded in the Frame as well.
See also parseAudioSprite() and previewAudioSprite() functions in META section of Docs.
NOTE
The sound can be made at any time but the app must be interacted with before the sound can be played.
This is a general Browser rule to stop being bombarded with sounds.
It means that you will have to make a start button or a splash page
that the user clicks or taps before a background sound can be played.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// There may be a security error when loading sounds locally for any Canvas app.
// Please read https://zimjs.com/tips.html#SOUND for easy solutions.
const click = new Aud("click.mp3"); // lazy-load a click sound
S.on("stagemousedown", ()=>{
click.play(); // plays everytime the stage is clicked (sigh)
});
EXAMPLE
// make a backing sound but do not play it
// the user must first interact at least once with a mousedown/click/tap/change
const backing = new Aud({file:"backing.mp3", loop:true});
let backingSound; // this will store the sound that is playing
// make a Toggle button that starts toggled off
new Toggle({label:"SOUND"})
.sca(.7)
.pos(30,30,LEFT,BOTTOM)
.change(e=>{
// play the sound if it has not played
// and toggle the instance's paused property if it has been played
if (!backingSound) backingSound = backing.play();
else backingSound.paused = !e.target.toggled;
});
EXAMPLE
// preload a couple sounds from an assets/ directory (path)
new Frame(FIT, 1024, 768, light, dark, ready, ["sound.mp3", "backing.mp3"], "assets/");
function ready() {
// show a Pane() to start so we know user has interacted before we play sounds
new Pane("START GAME", yellow).show(init); // this calls init when closed
function init() {
// now the user has interacted to close the pane
new Aud("backing.mp3", .3, true).play(); // volume of .3 and looping
// Make sounds only play once and start over when pressed again
// otherwise, the default is play the sound completely each press.
// If someone presses a lot - this is a lot of sounds playing at once.
// If we left the interrupt at "none" the sound would finish before playing again
// which is not optimal as we want the sound to start each time we press.
// We could add these to the Aud() parameters but here we use STYLE
STYLE = {maxNum:1, interrupt:"any"}
const sound = new Aud("sound.mp3");
new Circle().center().tap(()=>{
sound.play();
});
} // end init()
} // end frame ready
EXAMPLE
// lazy-load a sound from a PATH of "assets/"
PATH = "assets/"
const long = new Aud("long.mp3");
// press on the stage - note the true for once at end of event
S.on("stagemousedown", ()=>{
const sound = long.play({volume:.2});
// adjust the sound after...
timeout(2, ()=>{
sound.volume = 1;
});
timeout(4, ()=>{
sound.paused = true;
});
timeout(6, ()=>{
sound.paused = false;
});
sound.on("complete", ()=>{
F.color = red;
// lazy-load a woot sound from path of assets/ and play twice
new Aud("woot.wav").play({loopCount:2});
S.update();
});
}, null, true); // true for once then remove the event
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
file - |ZIM VEE| the String file name of the sound including file extension for instance, "sound.mp3"
There is a global PATH constant that can be set to add a path to the start of the file name
for instance setting PATH = "assets/" would then look for "assets/sound.mp3".
If a path is provided to Frame() parameter or the loadAssets() then these will automatically set the global PATH constant.
For an audioSprite use the label here.
** ALL THE PARAMETERS below can also be specified in the play() method (except for maxNum)
volume (default 1) - set the volume
loop (default false) - set to true to loop forever or a number based on loopCount
loopCount (default null) - change to how many times to play the sound
there is no need to set loop if loopCount is set
pan (default 0) - set towards -1 to pan left and towards 1 to pan right
may not work locally but should work on server
offset (default 0) - elapsed time in seconds to start playing
delay (default 0) - time to wait before sound is started
interrupt (default "none") - how to interrupt a sound if a sound with the same source is played
and the maximum number of instances of the sound are already playing
** must have maxNum set - see the maxNum property or the Frame(), loadAssets() or asset() maxNum parameter
"none" - do not interrupt the previously playing sound(s) (with the same source)
"any" - interrupt the previously playing sound(s) (with the same source)
"early" - interrupt only the previously playing sound that has progressed the least
"late" - interrupt only the previously playing sound that has progressed the most
** thank you CreateJS and SoundJS for providing these options
maxNum (default null) ONLY FOR LAZY LOAD - otherwise use maxNum in Frame() or F.loadAssets()
set to a number of instances that a sound can play.
The default is as many as the browser can handle (hundreds).
maxNum can also be set as Frame(), loadAssets() and asset() parameters.
Setting this to 1 will only play one instance of the sound at a time.
The interrupt setting determines what happens if the sound is played again while it is playing
if "none" is set (default) then it will not interrupt the current instance
if "any" is set then it will play the sound again from the start, etc.
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
play(volume, loop, loopCount, pan, offset, delay, interrupt) - play the sound
*** Supports ZIM DUO - regular parameters or single configuration object {}
*** returns a CreateJS AbstractSoundInstance (of course). Detailed docs are here:
*** https://www.createjs.com/docs/soundjs/classes/AbstractSoundInstance.html
*** See the methods and properties listed after the play parameters
volume (default 1) - set the volume
loop (default false) - set to true to loop forever or a number based on loopCount
loopCount (default null) - change to how many times to play the sound
there is no need to set loop if loopCount is set
pan (default 0) - set towards -1 to pan left and towards 1 to pan right
may not work locally but should work on server
offset (default 0) - elapsed time in seconds to start playing
delay (default 0) - time to wait before sound is started
interrupt (default "none") - how to interrupt a sound if a sound with the same source is played
and the maximum number of instances of the sound are already playing
** must have maxNum set when sound is loaded - see the Aud(), Frame(), loadAssets() or asset() maxNum parameter
"none" - do not interrupt the previously playing sound(s) (with the same source)
"any" - interrupt the previously playing sound(s) (with the same source)
"early" - interrupt only the previously playing sound that has progressed the least
"late" - interrupt only the previously playing sound that has progressed the most
** thank you CreateJS and SoundJS for providing these options
ABSTRACT SOUND INSTANCE
The return result of the play() makes a CreateJS AbstractSoundInstance
var sound = Aud("sound.mp3").play(); // sound is an AbstractSoundInstance
// note: if lazy-loaded then the result of a play() before the sound has loaded
// will be a proxy object with only volume and pan properties and will dispatch a complete event
// methods, other properties and events will only be available on a play() after the sound is loaded
METHODS (of AbstractSoundInstance)
** full docs here: https://www.createjs.com/docs/soundjs/classes/AbstractSoundInstance.html
** these methods are on the results of a new Aud().play() not on the new Aud()
const sound = new Aud();
const soundInstance = sound.play();
timeout(2, ()=>{soundInstance.stop()});
stop() - stops the sound and sets the time to 0
play() - plays the sound again - usually, the sound is already playing from the sound.play()
but if it is stopped - this will start it again
fade(volume, time, call) - fade in or out a playing sound in a time and call the call function when done
panSound(pan, time, call) - pan left (-1) or right (1) or in between a playing sound in a time and call the call function when done
PROPERTIES
type - holds the class name as a String
in this case the type is "Aud" but if the Aud is lazy-loaded then
it starts as type "AC" (Asset Container) and then when loaded becomes "Aud"
file - the filename used
src - the src used - path and file - available on complete event
item - the CreateJS data item used for preload - available on complete event
PROPERTIES (of AbstractSoundInstance)
** full docs here: https://www.createjs.com/docs/soundjs/classes/AbstractSoundInstance.html
** these properties are on the results of a new Aud().play() not on the new Aud()
const sound = new Aud();
const soundInstance = sound.play();
timeout(2, ()=>{soundInstance.volume = .5});
paused - set to true to pause and false to unpause
muted - set to true to mute - but sound keeps playing or false to unmute
volume - the volume with 1 being the default
pan - set from -1 (full left) to 1 (full right) with 0 in middle (may not work until on server)
position - set to place in sound in milliseconds (ZIM TIME constant does not affect this)
duration - the length of the sound in milliseconds
EVENTS
dispatches a "ready" or "complete" event when the sound is loaded
if preloaded this is dispatched 20 ms after the Aud is made
Note: the AbstractSoundInstance below also dispatches a "complete" event when the sound is finished playing
EVENTS (of AbstractSoundInstance)
** full docs here: https://www.createjs.com/docs/soundjs/classes/AbstractSoundInstance.html
complete - dispatched when the sound has reached the end - after any loops (not before)
loop - dispatched when the sound loops (but not at end of last loop - that is complete)
currently triggering at the first play too.
CLOSE ▲PAGE ▤CODE ▤TOUR😊
Vid
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Use Vid() to show a video. Use the play() method to start the video when loaded.
The user must interact with the app before play() will work.
There may be a security error when loading video locally for any Canvas app.
Please read https://zimjs.com/tips.html#VIDEO for easy solutions.
Vid will add an HTML 5 video and source tag in behind the scene
and pipe the video into a ZIM Bitmap which is shown in the Vid container.
Vid lets you pause() and play() and get the duration
or get and set the currentTime and volume.
A source property stores the HTML 5 video for more methods, properties and events.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
Vid also has a keyOut() method to key out a color from the video.
SEE: https://zimjs.com/zim/assets.html
Vid will give a "ready" and a "complete" event when ready to play.
NOTE
Vid is a container with a bitmap inside (see bitmap property).
This means that other objects can be added to the Vid object.
This is like the ZIM Shapes (Rectangle, Circle, etc.) which are containers and can have objects added to them.
If doing this, note that the container has its mouseChildren turned off
so when dragging, for instance, the whole vid moves rather than the bitmap inside the vid.
To interact with objects inside, set vid.mouseChildren = true.
Generally, for clarity, avoid adding objects to Shapes or Vids unless you are used to the mouseChildren setting.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// video is a container that will have a width of 800 and height of 600
// The video will be FIT inside these dimensions and centered by default
// Also see align and valign parameters
// At the start, it will have a type of "AC" once it loads it will be "Vid"
const video = new Vid("video.mp4", 800, 600)
.center() // using 800x600
S.on("stagemousedown", () => {
video.play();
});
EXAMPLE
// video is a container that will have a width of 800 and height of 600
// The video will be stretched to 800 by 600 - possibly changing the aspect ratio
const video = new Vid("video.mp4", 800, 600, FULL)
.center() // using 800x600
S.on("stagemousedown", () => {
video.play();
});
EXAMPLE
// video is a container with no width and height to start
// once the video is loaded the container will take the dimensions of the video
// and the center() will be called again to properly center the container
// just like lazy loading Pic().
const video = new Vid("video.mp4")
.center() // will automatically be re-centered after loading
S.on("stagemousedown", () => {
video.play();
});
EXAMPLE
// make the video cover the stage
const video = new Vid("video.mp4", W, H, FILL)
.center()
S.on("stagemousedown", () => {
video.play();
});
EXAMPLE
// load a video from the assets/ folder
PATH = "assets/"
// either provide width and height before scaleTo() or use the ready event
const video = new Vid("video.mp4", W, H).center();
video.on("ready", ()=>{
// video.keyOut("#01b03f", .2); // optional keyOut a green color
// do not play the video until we interact with the app
const pane = new Pane("VIDEO ON CANVAS!").show(()=>{
// this (the callback) runs when the pane is closed
video.play();
});
});
// toggle the pause of the video
video.on("mousedown", ()=>{
// note videoPaused property
// not paused (which is for animation)
video.pause(!video.videoPaused);
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
file - |ZIM VEE| the String file name of the image including file extension for instance, "pic.png"
There is a global PATH constant that can be set to add a path to the start of the file name
for instance setting PATH = "assets/" would then look for "assets/pic.png".
If a path is provided to Frame() parameter or the loadAssets() then these will automatically set the global PATH constant.
width - (default null) optionally predict the width of the video for placement before being loaded
The width will be ignored once the video is loaded.
To change the width of Vid, use siz() or sca() methods
or width, widthOnly, height, heightOnly, scale, scaleX and scaleY properties.
height - (default null) optionally predict the height of the Vid (see width for similar details)
scaling - (defaut FIT) how to scale video into dimensions if provided - otherwise
FIT - scales video to fit inside width and height keeping aspect ratio - also see align and valign
FILL - scales video to surround width and height keeping aspect ratio - also see align and valign
FULL - scales video width to width and video height to height possibly stretching aspect ratio
volume - (default 1) the volume of the video - also see the volume property
loop - (default false) set to true to loop the video
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
type - (default "video/mp4") the mime type or codec of the video
see https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
play() - play the video
pause(state) - pause the video if the state is true (default) or play again if state is false
keyOut(color, tolerance, replacement) - remove a certain color in the video and make it see-through - with a color tolerance between 0-1
the default color is "#389b26" which is a medium dark green
the default tolerance is .1 - the higher the tolerance the less sensitive the keying process - so more colors will be removed similar to the provided color
color and tolerance can be an array of colors and tolerances (or just one tolerance if all are the same)
replacement (default clear) a color to replace the keyed out color with or an optional array to match the colors array if an array is used
clone(exact) - clone the object - if using ZIM VEE values for file, use exact true to copy the picked ZIM VEE option.
dispose() - dispose the video including HTML tags, etc.
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
in this case the type is "Vid" but if no dimensions are provided
it starts as type "AC" (Asset Container)
and when the video is ready to play (see "complete" or "ready" event), the type is set to "Vid"
file - the filename used
duration - get the duration of the video in seconds
currentTime - get or set the current time in seconds
volume - get or set the volume of the video
videoPaused - get if the video is paused
bitmap - reference to the the ZIM Bitmap inside the container
source - reference to the HTML video tag with all sorts of methods, properties and events
use this for the fastSeek() method if currentTime property is too slow
see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/videoALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the "ended" event on the HTML video tag (source)
dispatches a "complete" and a "ready" event (use either one) when the image is loaded.
if preloaded this is dispatched 20 ms after the Vid is made.
Also see HTML video events: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#events
which has an "ended" event on the source property...
so use myVideo.source.addEventListener("ended", ()=>{});
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
SVG
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Use SVG() to show an SVG tag or file on the Canvas.
There are two options, the default is as a Bitmap
or choose an SVGContainer with Blob, Squiggle, and transformable shapes.
Before ZIM version ZIM 00, svgToBitmap() or SVGContainer() was used to show SVGs.
These can still be used if desired. The SVG() class just wraps these.
SEE: https://zimjs.com/zim/assets.htmlNOTE
ZIM has Squiggle() and Blob() which often can replace the need for SVG() and has many more benefits.
These can be made with ZIM Pizzazz 4 at https://zimjs.com/paths
Or an SVG path can be passed directly to the points parameter of a Blob or Squiggle.
Squiggles and Blobs let the user:
turn the paths editable
animate objects on the path
add Beads to the path
animate the path
shape animate the path to another path
do hitTestPath on the path
We recommend using SVG only when there is already an SVG that image you want to use.
PRELOADING
It is recommended that you preload SVG files using the Frame() assets and path parameters.
After the frame loads, SVG files can also be loaded on demand with F.loadAssets().
Batch loading SVGs is more efficient and the width and height will be available when the Frame() is "ready" or loadAssets() is "complete".
LAZY-LOADING
If SVGs are not preloaded then SVG() will use automatic loading (lazy-loading).
If width and height are provided, all will go smoothly.
If width and height are not provided, ZIM will store various scaling and positioning commands
and re-apply the commands once the images are loaded.
This happens for center(), centerReg(), pos(), scaleTo(), outline() and perhaps others.
This extra work is NOT required if assets are preloaded or a width and height are provided.
Some controls like Tile() and Scroller() must have dimensions and will give a warning in the console.
In the past there has been issues with cloning lazy-loaded objects before they are loaded, but this should work now.
SVG will give a "ready" and a "complete" event when loaded.
These events are triggered 20 ms after making the object if the object is already preloaded.
NOTE
SVG is a container with a bitmap inside (see bitmap property)
or if the bitmap option is not selected there are other shapes inside.
This means that other objects can be added to the SVG object.
This is like the ZIM Shapes (Rectangle, Circle, etc.) which are containers and can have objects added to them.
If doing this, note that the container has its mouseChildren may be turned off
so when dragging, for instance, the whole SVG moves rather than the bitmap inside the SVG.
To interact with objects inside, set pic.mouseChildren = true.
Generally, for clarity, avoid adding objects to Shapes, Pics SVGs unless you are used to the mouseChildren setting.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// lazy-load an SVG
new SVG("file.svg").center().drag();
EXAMPLE
// assuming there is an SVG tag on the page - could be display:none
new SVG(zid("svgTagID")).center().drag();
EXAMPLE
// Find the SVG in an assets/ folder
PATH = "assets/"
// Tile a lazy-loaded SVG with dimensions - otherwise Tile would give a console warning
new Tile(new SVG("file.svg", 100, 100), 4, 4)).center();
// but the dimensions might not be right and the tile could look odd once the SVGs are loaded
// would be better to preload - see next example
EXAMPLE
// pre-load and Tile an SVG
new Frame(FIT, 1024, 768, light, grey, ready, "file.svg", "assets/");
function ready() {
new Tile(new SVG("file.svg"), 4, 4)).center();
}
EXAMPLE
// add an SVGContainer from an SVG string
// this would make a simple Squiggle line with editable points
// see the Docs under SVGContainer for more complex examples and added information
// note the h t t p : should be edited to not have spaces - just avoiding Doc auto linking
const svg = `<svg width="150" height="200" xmlns="h t t p ://www.w3.org/2000/svg">
<path id="lineAB" d="M 0 0 l 150 200" stroke="red" stroke-width="3" fill="none" />
</svg>`;
new SVG(svg, null, null, false).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
svg - |ZIM VEE| the String file name of the SVG including file extension for instance, "pic.svg"
or an SVG tag either directly as a string or as a reference to an HTML tag - ie. zid("svgID")
There is a global PATH constant that can be set to add a path to the start of the file name
for instance setting PATH = "assets/" would then look for "assets/pic.svg".
If a path is provided to Frame() parameter or the loadAssets() then these will automatically set the global PATH constant.
width - (default null) optionally predict the width of the SVG
The width will be ignored and the actual width will be used if the SVG is preloaded
and if lazy-loaded, the width will be replaced with the actual width after the SVG is loaded.
So the width is only used to tell something like a Tile(), what size to expect before the SVG is loaded.
To change the width of an SVG, use siz() or sca() methods
or width, widthOnly, height, heightOnly, scale, scaleX and scaleY properties.
height - (default null) optionally predict the height of the SVG (see width for similar details)
bitmap - (default true) this will show the SVG as a Bitmap (still nicely scalable!)
or set to false to use an SVGContainer() which converts the SVG to Blob, Squiggle and ZIM Shapes with transforms.
This allows for editable paths - but perhaps not all aspects of SVGs are supported such as CSS styles on SVGs.
Alternatively, a single SVG path can be passed to a ZIM Blob() or Squiggle() and SVG() can be avoided.
** these parameters are NOT for the bitmap option but rather for the SVGContainer
splitTypes - (default false) - set to true to split different types of paths into separate objects
geometric - (default true) - set to false to load Rectangle and Circle objects as Blob objects
showControls - (default true) set to false to start with controls not showing
interactive - (default true) set to false to turn off controls, move, toggle, select, edit - leaving just the shapes
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
keyOut(color, tolerance, replacement) - for Bitmap setting - remove a certain color in the SVG and make it see-through - with a color tolerance between 0-1
the default color is "#389b26" which is a medium dark green
the default tolerance is .1 - the higher the tolerance the less sensitive the keying process - so more colors will be removed similar to the provided color
color and tolerance can be an array of colors and tolerances (or just one tolerance if all are the same)
replacement (default clear) a color to replace the keyed out color with or an optional array to match the colors array if an array is used
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
in this case the type is "SVG" but if the SVG is lazy-loaded then
it starts as type "AC" (Asset Container) if no dimensions are provided
or "ACWD" (Asset Container With Dimensions) until the SVG is loaded
at which point, the type is set to "SVG"
bitmap - reference the the ZIM Bitmap inside the container.
this exists for both the bitmap setting and the SVGContainer setting
but with the SVGContainer setting, the bitmap is not added to the container
svg - reference to the SVG code
file - the filename used
src - the source with path and filename - available on complete event
item - the CreateJS data item used for preload - available on complete event
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "complete" and a "ready" event (use either one) when the SVG is loaded.
if preloaded this is dispatched 20 ms after the SVG is made.
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
Speech
zim class - extends a createjs.EventDispatcher
DESCRIPTION
Create a new Speech() and use talk() or listen()
The talk() will speak words
The listen() will turn voice into words
This is a short wrapper class for the Web Speech API
https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API
Thanks Karel Rosseel for the initial research on Speech.
SEE: https://zimjs.com/016/speech.htmlNOTE
The listen() method is currently not supported by Apple iOS Web - only Native apps (grr)
But the talk() method works on iOS and Android Web - however, there seems to be one voice.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const speech = new Speech();
// interact at least once before talking
new Button({label:"TALK"}).center().tap(()=>{
speech.talk("Hello World");
});
EXAMPLE
// let user pick a voice
const speech = new Speech();
// interact at least once before talking
new Button({label:"TALK"}).center().mov(0,-120).tap(()=>{
speech.talk("Hello World!", list?list.text:null);
});
let list;
speech.on("voiceschanged", ()=>{ // must wait for voices to be loaded
if (list) list.dispose(); // seems to run only once but just in case
list = new List(500,300,speech.voices,6).center().mov(0,120);
S.update();
});
EXAMPLE
const speech = new Speech();
new Button({label:"LISTEN"}).center().tap(()=>{
// Note: iOS does not support
speech.listen();
});
speech.on("result", e=>{
label.text = e.words;
S.update();
})
const label = new Label({align:CENTER, text:""}).reg(CENTER).pos(0,200,CENTER,BOTTOM);
METHODS
talk(text, voice, volume, lang, rate, pitch) - the computer will say the words
returns an utterance object on which all these parameter can be dynamically set including the words
text - the text to say (or see Web Speech API for special formats)
voice (default "Microsoft David - English (United States)") - the voice
also see "voiceschanged" event at which point speech.voices will be a list
the voices do not need to be loaded if using the default voice
volume (default 1) the volume of the voice
lang (default user system language) the language of the voice
rate (default 1) the rate of the voice
pitch (default 1) the pitch of the voice
stopTalking() - stop talking
pauseTalking() - pause talking
resumeTalking() - resume talking ;-)
getVoices() - called automatically when the the Voice's voiceschanged event triggers
his is set automatically but may take a second or two to load
listen(interim, language) - start listening to the mic to record what is said
this will dispatch a "result" event on the Speech object
interim defaults to true and means it gives a results as each word is spoken
set interim to false to give a result only after speaking is done (or a pause in speaking)
the result event object (often e is used) will have a words property with the words
and a confidence property with a percent as to how confident the match
stopListening() - stop listening
PROPERTIES
type - holds the class name as a String
voices - an array of string voices available for talk() - loads when "voiceschanged" event is dispatched (automatically set)
voiceObjects - an array of voice objects with name and lang properties used internally by talk() - matches voices indexes
voiceLanguages - an array of languages for the voices - matches voices indexes
recognition - the SpeechRecognition() object created (used internally) has JS properties - see:
https://wicg.github.io/speech-api/#speechreco-attributes
for instance, set the default language as mySpeech.recognition.language = "en-US";
EVENTS
dispatches a "voiceschanged" event when voices property will be ready - not needed if just using default voice
dispatches "result" when either as each word is spoken if listen() is used (interim defaults to true)
or at the end of speaking words if listen(false) is used (interim is set to false)
the result event will have an event object (often e is used) that holds a words property with the words spoken
and a confidence property that is a ratio (0-1) for confidence in the result
Note: iOS (at this time) does not support the listen() and result event
dispatches "speechend" events when listen() has detected an end to the talking
dispatches an "error" event if no words are spoken, etc. the event object has an error property with the error message
dispatches "start", "end" and "error" on the utterance object returned by talk()
Note: there are more features to the Web Speech API - see the HTML docs
CLOSE ▲PAGE ▤CODE ▤
Fonts
For a Label object or components with labels
DESCRIPTION
As of ZIM ZIM 02, custom fonts can be loaded by their file name without the need for a font object {}.
Custom fonts must be preloaded in the Frame() or loadAssets() assets parameter.
Supported fonts are "ttf","otf","woff2","woff","fnt" files and Google fonts.
The font is then available to Label and components with labels.
ZIM wraps the CreateJS PreloadJS library to offer simplified loading.
NOTE
do not use uppercase letters on font name or extension - seems to not load on mobile.
NOTE
system fonts can be used without loading the font.
**************
DO NOT make a new Font() - rather, pass the font information into the Frame assets parameter.
Or load fonts when desired with Frame loadAssets() and wait for a complete event.
In either case, the font will then be available for Labels
**************
EXAMPLE
new Frame({ready, assets:"Reuben.otf", path:"assets/"});
function ready() {
new Label("Custom Font", 30, "Reuben").center();
}
EXAMPLE
// here is the same but with the font object - used pre ZIM ZIM 02 - this still works
new Frame({ready, assets:{font:"Reuben", src:"Reuben.otf"}, path:"assets/"});
function ready() {
new Label("Custom Font", 30, "Reuben").center();
}
EXAMPLE
// use a Google font https://fonts.google.com/ and apply it with a STYLE
// previously, the whole URL was needed:
// new Frame(FIT, 1024, 768, red, dark, ready, "https://fonts.googleapis.com/css?family=Dancing+Script");
// now, the gf_ shortcut can be used:
new Frame(FIT, 1024, 768, red, dark, ready, "gf_Dancing+Script");
function ready() {
STYLE = {font:"Dancing Script"}; // or include + but not necessary.
new Label("Custom Google Font").center();
new Label("Second Custom Google Font").center().mov(0,100);
}
EXAMPLE
// with loadAssets, the previous example would be:
F.loadAssets("gf_Dancing+Script");
F.on("complete", ()=>{
new Label("Custom Google Font", 50, "Dancing Script").center();
});
Keys
"keydown" and "keyup" Frame events
DESCRIPTION
The Frame has a "keydown" and "keyup" events to capture key presses
and a keyboardMessage() method to prompt for keyboard interactivity.
When an app is first loaded it cannot receive keyboard events until it is interacted with.
Interaction must be a mousedown or click - not just an over or move interaction.
Often, we will make an intro Pane() or play Button() for a game, for instance, before playing sounds.
In ZIM 014 we added a keyboardMessage() method to prompt for an interaction so key events are activated.
Also see ZIM Keyboard(), TextEditor(), TextInput() and MotionController() for various keyboard functionality.
EXAMPLE
keyboardMessage(); // will prompt for keyboard control
F.on("keydown", e=>{
zog(e.key) // a string of the keypress
zog(e.keyCode) // the numeric code of the keypress (older but used in lots of examples)
zog(F.altKey) // true if alt is pressed - also: ctrlKey, metaKey, shiftKey
});
// for controlling a game object with keyboard please see MotionController(obj, "keydown")
// as the MotionController solves a few tricky issues with key control
Cursors
Frame property
DESCRIPTION
In ZIM 014 we added support for custom cursors as a Frame property
to get or set an object literal with custom cursors that 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 specify which cursor is on an object.
drag(), tap(), etc. will already work with the custom cursor system
set F.cursors = null to turn off custom cursors
There is a Frame cursorsExclude() method to exclude certain objects from the custom cursors.
There is a Frame cursorObj property to indicate the current custom cursor.
EXAMPLE
F.cursors = {
// the default cursor will be an emitter
default:new Emitter({
obj:new Circle({min:3,max:8},white),
force:1,
gravity:0
}),
box:new Rectangle(40,40,clear,white,8,0,true)
.reg(CENTER)
.animate({props:{dashedOffset:-110}, rewind:true, loop:true})
}
const rect = new Rectangle(500,500,red).center().cur("box"); // apply the box cursor
Tilt
"devicemotion" and "deviceorientation" Frame events
DESCRIPTION
The Frame has a "devicemotion" event to capture device tilt
and a "deviceorientation" to capture device rotation (like a compass)
Also see the PermissionAsk() class which will handle asking for permission on iOS devices.
NOTE
For either event the Frame sensors parameter MUST be set to true
EXAMPLE
// for capturing tilt on device (rotation about an axis)
// also SEE the PermissionAsk example below
// also set Frame sensors parameter to true
// and be on a mobile device
const label = new Label().center();
F.on("deviceorientation", e=>{
label.text = e.rotation.x +","+ e.rotation.y +","+ e.rotation.z;
S.update();
});
EXAMPLE
// on iOS, the sensors must be allowed first - this example works for all devices
const permissionType = "deviceorientation"; // or "devicemotion"
const ask = new PermissionAsk(init, permissionType);
function init(yes) {
// if the user answers yes to the PermissionAsk
const errorPane = new Pane("SENSOR not available",yellow);
if (yes) {
// use the sensors
label.text = decimals(e.rotation.x) +","+ decimals(e.rotation.y) +","+ decimals(e.rotation.z);
S.update();
} else { // answered no to PermissionAsk dialog
errorPane.show();
}
}
EXAMPLE
// for shaking motion - ALSO see the PermissionAsk example above for iOS
// and replace "deviceorientation" with "devicemotion"
// and replace e.rotation.x, etc. with e.acceleration.x etc.
// also set Frame sensors parameter to true
// and be on a mobile device
const label = new Label().center();
F.on("devicemotion", e=>{
label.text = e.acceleration.x +","+ e.acceleration.y +","+ e.acceleration.z;
S.update();
});
EVENTS
"devicemotion" - for tilt (also set Frame sensors parameter to true)
fired on moving mobile device - like a tilt or shake - eventObject.acceleration holds x, y and z properties of motion
"deviceorientation" - for rotation (also set Frame sensors parameter to true)
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
CLOSE ▲PAGE ▤CODE ▤
PermissionAsk
zim class - extends a zim.Pane which extends a zim.Container
DESCRIPTION
A circular confirmation widget to ask the user if they want a permission for iOS.
For some iOS permissions, the app needs to be interactive with first before permission can be asked!
This is for iOS only - if not in iOS then will just pass through the test.
NOTE
this started as SensorAsk but the class has been adjusted to handle other permissions and the name has been changed in ZIM 016
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// on iOS, the sensors must be allowed first
const permissionType = "deviceorientation"; // or "devicemotion"
const ask = new PermissionAsk(init, permissionType);
function init(yes) {
// if the user answers yes to the PermissionAsk
const errorPane = new Pane("SENSOR not available",yellow);
if (yes) {
// use the sensors
const label = new Label({text:"test on mobile", align:CENTER}).centerReg();
F.on("devicemotion", e=>{
// use the sensors
label.text = decimals(e.rotation.x) +","+ decimals(e.rotation.y) +","+ decimals(e.rotation.z);
S.update();
})
} else { // answered no to PermissionAsk dialog
errorPane.show();
}
}
EXAMPLE
// goes right to permissions on computer and android
// pops up a PermissionAsk Pane on iOS then if yes, goes to permissions on iOS
new PermissionAsk(init, "cam");
function init(val) {
new Label(val).center(); // media stream if yes to permissions otherwise false
S.update();
}
EXAMPLE
// on iOS, the app must be interacted with before using mic or cam
// this goes right to permissions on computer and android
// but pops up a PermissionAsk Pane on iOS then if yes, goes to permissions on iOS
new PermissionAsk(init, "mic"); // or "cam" or "miccam"
function init(val) {
zog(val); // media stream if yes to permissions otherwise false
S.update();
}
PARAMETERS - accepts ZIM DUO regular parameters in order or a configuration object with parameters as properties
callback - the function to callback when permission is accepted
if the permissionType is deviceorientation or devicemotion this will receive true for accept or false for no permission
if the permissionType is audio, video or audiovideo this will receive a stream if accepted or false if not
for not iOS, the system permissions will appear
for iOS the PermissionAsk Pane will be shown and the system permissions
in all cases, the callback will be called on result
the parameter given to the callback will be true (sensors) or a media stream (mic / cam) or false if not accepted
permissionType - (default "deviceorientation") the string deviceorientation, devicemotion, mic, cam, or miccam
color - (default zim.dark) the font and border color of the widget
backgroundColor - (default zim.lighter) the backgroundColor of the widget
METHODS
dispose() - dispose the PermissionAsk
ALSO
see all the methods of a zim Pane()
including hide()
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - name of class as a string
permissionType - the type of permission requested
label - reference to the zim Label
yes - reference to the zim Button with YES
no - reference to the zim Button with NO
ALSO
see ZIM Pane for properties such as:
backdropColor, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
CLOSE ▲PAGE ▤CODE ▤
Colors - orange, green, pink, blue, brown, yellow, purple, red, interstellar, black, darker, licorice, dark, charcoal, grey, gray, granite, tin, pewter, silver, fog, mist, light, moon, lighter, wh¡te, faint, clear
zim constants (lowercase)
DESCRIPTION
ZIM colors for convenience - such as blue, green, dark, etc.
Traditional HTML colors as strings can also be used such as "blue", "tomato", etc.
Also available are HEX numbers as strings such as "#333" or "#cc0000"
and RGB and RGBA of 0-255 values for red, green, blue with 0 being no color and 255 being full color
then alpha from 0 to 1 as a decimal with 0 being transparent to 1 being opaque.
These are in a string such as "rgb(0,0,255)" or "rgba(0,0,0,.2)" (.2 is alpha)
NOTE
These DO NOT require the zim namespace, even if zns=true is set or if using node modules without zimplify()
NOTE
ZIM colors started off as properties of the frame so F.blue
but the frame properties have now been removed as they are stored on the zim namespace and as globals
FAINT AND CLEAR
faint is "rgba(0,0,0,.01)" which is the faintest color that can be interacted with
clear is "rgba(0,0,0,0)" which is invisble but cannot be interacted with
However, clear can be used along with expand(0) to be able to interact with an object
where the expand(0) (or whatever padding is desired) adds a CreateJS hitArea.
DARKEN AND LIGHTEN
ZIM has added darken() and lighten() methods to the JS String prototype to handle easy darkening and lightening of colors
This is very handy in desiging.
https://zimjs.com/docs.html?item=darkenhttps://zimjs.com/docs.html?item=lighten
COLOR BLENDS
ZIM has toColor() to move one color towards another color
https://zimjs.com/docs.html?item=toColor
ALPHA
ZIM has toAlpha() to set the alpha of colors
https://zimjs.com/docs.html?item=toAlpha
GRADIENTS
ZIM DisplayObjects accept GradientColor(), RadialColor() and BitmapColor() objects - see docs under the CODE module for info.
https://zimjs.com/docs.html?item=GradientColorhttps://zimjs.com/docs.html?item=RadialColorhttps://zimjs.com/docs.html?item=BitmapColorNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Circle(100, blue).center();
// is the same as
new Circle(100, "#50c4b7").center();
// ZIM colors (or HTML colors) can have alpha adjusted as follows:
new Circle(100, blue.toAlpha(.5)).center();
// colors can be darkened or lightened using darken() or lighten()
new Circle(100, blue.darken(.5)).center();
// colors can be blended using toColor()
new Circle(100, blue.toColor(red, .2)).center();
Constants - FIT, FILL, FULL, LEFT, RIGHT, CENTER, MIDDLE, START, END, TOP, BOTTOM, OVER, UNDER, HORIZONTAL, VERTICAL, BOTH, RANDOM, RADIAL, UP, DOWN, NEXT, PREV, AUTO, DEFAULT, ALL, NONE, AVE, GET, POST, LOCALSTORAGE, SOCKET, TO, FROM, BOTH, SINE, SQUARE, TRIANGLE, SAW, ZAP, IGNORE
zim constants
DESCRIPTION
ZIM positioning, data and sound constants for convenience if desired.
These DO NOT require the zim namespace, even if zns=true is set or if using node modules without zimplify()
These are all equal to strings with lowercase values.
So using TOP is the same as using "top"
Positioning: FIT, FILL, FULL, LEFT, RIGHT, CENTER, MIDDLE, START, END, TOP, BOTTOM, OVER, UNDER, HORIZONTAL, VERTICAL, BOTH, RANDOM, RADIAL, UP, DOWN, NEXT, PREV, AUTO, DEFAULT, ALL, NONE, AVE
Data: GET, POST, LOCALSTORAGE, SOCKET, TO, FROM, BOTH
Sound: SINE, SQUARE, TRIANGLE, SAW, ZAP
Style: IGNORE
NOTE
there are a set of constants at the start of the CONTROLS module as well
NOTE
for START and END, see DIR constant under CONTROLS module.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Tip("hello", RIGHT, MIDDLE).show();
// same as
new Tip("hello", "right", "middle").show();
Globals - F, S, W, H, M
zim globals
DESCRIPTION
F, S, W, H, M are globals given when using ZIM Frame.
There are also globals for the ZIM CONSTANTS and ZIM Colors - see the Docs above
and a few variables and functions listed under ALL INITIAL GLOBALS below.
The globals NEVER require the zim namespace and are global in the JavaScript window scope.
ZIM has a method called zimplify() that can make all ZIM classes, functions and properties global.
zimplify() loops through all properties on the zim namespace and adds them to the JavaScript window.
Examples are Frame(), Button(), center(), STYLE, Emitter(), etc.
zimplify() is automatically run when using the CDN ES module or script tags
unless the global variable zns is set to true before importing ZIM.
If zns is set to true, then the zim namespace is required: zim.Frame(), etc.
If using NPM, then zimplify() is NOT automatically run, and the zim namespace is required,
but zimplify() can be used at the top to turn all ZIM classes, functions and properties global.
NOTE
there are a set of constants at the top of the CONTROLS module like STYLE, PATH, TIME, etc.
These are NOT global unless zimplify() is run.
So default global for ES module and scripts but default NOT global for NPM
ADDED ZIM ZIM 01:
F - the ZIM default frame - also there is a zimDefaultFrame and zdf global variable made - but F is easier.
the ZIM default frame is the first frame made - or the frame that last has the setDefault() method called
S - the Stage of the default frame - this will be the stage that addTo(), center(), etc. get added to if no container is provided
W - the width of the default frame - this will be updated automatically in FULL mode on window resize.
H - the height of the default frame - this will be updated automatically in FULL mode on window resize.
M - false if not on mobile, otherwise reports the mobile device "iOS", "android", etc. - can also use mobile().
There are many previous examples that declare frame, stage, stageW and stageH
this technique can still be used but you are welcome to use the F, S, W, H if desired.
ALL INITIAL GLOBALS:
WW (JavaScript window - saves 1.5K as window reference is not minified)
createjs (namespace)
zim (namespace)
zns (zim name space - set to true before importing ZIM to require namespace)
zon (set to false before importing ZIM to stop all console messages)
zimBlob (used to avoid import conflict with JS Blob)
zimWindow (used to avoid import conflict with JS Window)
z_i (global iterator - reused rather than declaring i all the time)
z_d (function for ZIM Distill - like tree-shaking)
isDUO (used for ZIM DUO technique)
zimify (turn ZIM functions into methods as of in ZIM 4TH)
zimplify (function that adds all ZIM Objects to the global namespace)
zimDefaultFrame (an original global reference to the default frame)
zdf (the shortened reference to the default frame)
F, S, W, H, M (frame, stage, stageW, stageH, mobile)
ZIM WRAP module of short globals starting with z - See the WRAP section of the DOCS
zog, zid, zss, zgo, zum, zot, zop, zil, zet, zob, zik, zta, zor
zog has zogr, zogb, zogg, etc, for logging with various colors
ZIM CONSTANTS: See CONSTANTS entry in the Docs above.
ZIM Colors: See Colors entry un the Docs above.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Frame({ready});
function ready() {
const c = new Circle().pos(W*.2, H*.2);
F.on("keydown", e=>{
c.sca(rand(.5,3));
S.update();
zog(M); // false if on desktop/laptop
});
}
Stage
zim class - extends a createjs.Stage which extends a createjs.Container
DESCRIPTION
An extension of a createjs.Stage that includes read only type, width and height properties, loop and hitTestGrid methods.
When using zim.Frame, there should be no reason to make a zim.Stage.
This was put in place to match the ZIM TypeScript typings for stage width and height.
Also see https://www.createjs.com/docs/easeljs/classes/Stage.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const stage = new Stage("canvasID");
PARAMETERS
canvasID - (default null) string ID for canvas tag
touch - (default false) set to true for touch on mobile
will be multitouch unless singleTouch is set to true
singleTouch - (default false) set to true for single touch
will override touch setting and turn touch to true but with single touch
METHODS
loop(call, reverse, step, start, end) - see the ZIM Display Methods loop() for details
see the ZIM Display Methods loop() for details
hitTestGrid(width, height, cols, rows, x, y, offsetX, offsetY, spacingX, spacingY, local, type)
see the ZIM Display Methods hitTestGrid() for details
disposeAllChildren() - remove and dispose all children
See the CreateJS Easel Docs for Stage methods, such as:
clear, update, toDataURL
And all the Container methods such as:
on, off, setBounds, getBounds, globalToLocal, etc.
PROPERTIES
frame - if made with ZIM Frame then frame points to the frame that made the stage
type - holds the class name as a String
width - read only width set by ZIM Frame
height - read only height set by ZIM Frame
ALSO
see the CreateJS Easel Docs for Stage properties, such as:
autoClear, canvas, nextStage, etc.
and all the Container properties, such as:
children, mouseChildren, filters, cacheCanvas, etc.
Note: also makes a partial zdf allowing circle.center() to work
but will be overwritten if an actual Frame is made
EVENTS
See the CreateJS Easel Docs for Stage events, such as:
mouseenter, mouseleave, stagemousedown, stagemousemove, stagemouseup, drawstart, drawend, etc.
and all the Container events such as:
click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
StageGL
zim class - extends a zim.Stage which extends a createjs.Stage
DESCRIPTION
An extension of a zim.Stage for WebGL support
See ZIM Stage and https://www.createjs.com/docs/easeljs/classes/StageGL.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const stage = new StageGL("canvasID", {preserveBuffer:true, antialias:true});
PARAMETERS
canvasID - (default null) string ID for canvas tag
options - (default null) an object literal with the following properties
FROM https://www.createjs.com/docs/easeljs/classes/StageGL.html
preserveBuffer (default false)
If true, the canvas is NOT auto-cleared by WebGL (the spec discourages setting this to true). This is useful if you want persistent draw effects.
antialias (default false)
Specifies whether or not the browser's WebGL implementation should try to perform anti-aliasing. This will also enable linear pixel sampling on power-of-two textures (smoother images).
transparent (default false)
If true, the canvas is transparent. This is very expensive, and should be used with caution.
premultiply (default false)
Alters color handling. If true, this assumes the shader must account for pre-multiplied alpha. This can help avoid visual halo effects with some assets, but may also cause problems with other assets.
autoPurge (default 1200)
How often the system should automatically dump unused textures with purgeTextures(autoPurge) every autoPurge/2 draws. See purgeTextures for more information.
touch - (default false) set to true for touch on mobile
will be multitouch unless singleTouch is set to true
singleTouch - (default false) set to true for single touch
will override touch setting and turn touch to true but with single touch
METHODS
loop(call, reverse, step, start, end) - see the ZIM Display Methods loop() for details
see the ZIM Display Methods loop() for details
hitTestGrid(width, height, cols, rows, x, y, offsetX, offsetY, spacingX, spacingY, local, type)
see the ZIM Display Methods hitTestGrid() for details
disposeAllChildren() - remove and dispose all children
See the CreateJS Easel Docs for StageGL methods:
https://www.createjs.com/docs/easeljs/classes/StageGL.htmlPROPERTIES
frame - if made with ZIM Frame then frame points to the frame that made the stage
type - holds the class name as a String
width - read only width set by ZIM Frame
height - read only height set by ZIM Frame
See the CreateJS Easel Docs for Stage properties:
https://www.createjs.com/docs/easeljs/classes/StageGL.html
Note: also makes a partial zdf allowing circle.center() to work
but will be overwritten if an actual Frame is made
EVENTS
See the CreateJS Easel Docs for StageGL events, such as:
mouseenter, mouseleave, stagemousedown, stagemousemove, stagemouseup, drawstart, drawend, etc.
and all the Container events such as:
click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊VIDS
Container
zim class - extends a createjs.Container
DESCRIPTION
A Container object is used to hold other display objects or other containers.
You can then move, rotate, scale and skew the container and all objects inside will transform accordingly.
You can apply an event on a container and use the target property of the event object
to access the object in the container that caused the event
or use the currentTarget property of the event object to access the container itself.
Containers do not have bounds unless some items in the container have bounds -
at which point the bounds are the combination of the bounds of the objects with bounds.
You can manually set the bounds with setBounds(x,y,w,h) - read the CreateJS docs.
Or pass in width and height, or boundsX, boundsY, width, height to have Container set bounds.
Manually set bounds will not update automatically unless you setBounds(null).
NOTE
All the ZIM shapes and components extend the Container.
This means all shapes and components inherit the methods and properties below
and indeed, the Container inherits all the createjs.Container methods and properties.
See the CreateJS documentation for x, y, alpha, rotation, on(), addChild(), etc.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const container = new Container().loc(100,100);
// demonstration of adding drag() to a Container
const rect = new Rectangle(100, 100, blue)
.addTo(container); // add rectangle to container
const circle = new Circle(40, red)
.center(container) // add the circle to the container and center
container.drag(); // will drag either the rectangle or the circle
container.drag({all:true}); // will drag both the rectangle and the circle
// below will reduce the alpha of the object in the container that was clicked (target)
container.on("click", e => {e.target.alpha = .5; S.update();});
// below will reduce the alpha of all the objects in the container (currentTarget)
container.on("click", e => {e.currentTarget.alpha = .5; S.update();});
EXAMPLE
// Here we apply the normalize() method of the Container to a Tile (which is a Container)
// and scale the children based on the resulting ratio
const tile = new Tile(new Rectangle(70,70,white,black).reg(CENTER), 9, 1, 20)
.normalize("x", CENTER)
.center();
// scale the items based on the distance from the center
// note, could set the strokeObj:{ignoreScale:true} param of Rectangle above too
tile.loop(item=>{
zogy(decimals(item.ratio)); // 0, .3, .5, .8, 1, .8, .5, .3, 0
item.sca(.5 + item.ratio*2);
});
// adjust the spacing by re-tiling the scaled items
const final = new Tile({
obj:tile.items,
cols:tile.items.length,
rows:1,
spacingH:-10,
unique:true, // make sure we do not pick (ZIM VEE) from the array
valign:CENTER
}).center()
tile.dispose();
final.sortBy("ratio"); // make more central objects come to front
EXAMPLE
// In this case we animate the children based on the rate
// animate() the rate and use sequence:0 to apply different speed to each item
const tile = new Tile(new Rectangle(10, 10, series(green,blue,yellow)), 20, 20, 5, 5)
.normalize("reg", CENTER)
.center()
.noMouse()
.animate({
props:{scale:2},
time:2,
ease:"elasticOut",
rate:target=>{return 1 + target.ratio*4},
sequence:0 // turn on per item animation
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** Container has a, b, c, d parameters to set x, y, width and height
There are two settings that are more common than providing all four parameters:
1. provide no parameters to make a Container with bounds that grow with content.
2. provide a and b only to make a Container with a width and height (and bounds with x and y of 0)
Here is what happens when you provide 1, 2 or all of the a,b,c,d parameters:
a - (default null) - width and height will be equal to parameter a (x and y will be 0)
or provide a ZIM Boundary() object or createjs Rectangle() object with x, y, width and height properties
a, b - (default null) - the width and height (x and y will be 0)
this is the normal way to make a container with a starting width and height
a, b, c, d - (default null) - the x, y, width and height of the bounds
if parameter a is not set, then the Container will take bounds that grow with its content
the bounds of the Container can be set at any time with setBounds(a, b, c, d)
if the bounds are set, then the Container bounds will not change as content is added
the bounds can be removed with setBounds(null) and the Container will get auto bounds
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
* This class has all the DISPLAY METHODS introduced in ZIM 4TH
* the methods are available to all ZIM Display objects that extend a ZIM Container
* such as ZIM Rectangle, Circle, Triangle, BLob
* as well as all components like: Label, Button, Slider, Dial, Tab, Pane, etc.
* as well as the ZIM display wrappers: Container, Shape, Sprite, MovieClip and Bitmap
cache(width||x, height||y, null||width, null||height, scale, options, margin, rtl, willReadFrequently) - overrides CreateJS cache() and returns object for chaining
** Supports ZIM DUO
If you do not provide the first four parameters, then the cache dimensions will be set to the bounds of the object
width||x - (default getBounds().x) the width of the chache - or the x if first four parameters are provided
height||y - (default getBounds().y) the height of the chache - or the y if first four parameters are provided
width - (default getBounds().width) the width of the chache - or null if first two parameters are provided
height - (default getBounds().height) the height of the chache - or null if first two parameters are provided
scale - (default 1) set to 2 to cache with twice the fidelity if later scaling up
options - (default null) additional parameters for cache logic - see CreateJS somewhere for details
also added adjustBounds property for options - set to true to set new bounds and registration point
on cached objects with x,y,width,height different than the original
this appears to NOT be the default with createjs cache() which keeps the original registration point and bounds
automatically fixing this changes lots of things so use the adjustBounds option when needed
for instance when caching parts of a container and requiring hit tests or the part to be draggable, etc.
margin - (default 0) add or subtract a margin from the bounds
eg. margin:10 will make the cache size 10 pixels more on all sides
this can be handy when caching objects with borders - that go half outside the natural bounds
rtl - (default null) set to true to use right to left
willReadFrequently - (default null) set to true if planning on using operations with getImageData() or toDataURL()
if you get a warning in the console about willReadFrequently then set this to true
updateCache() - updates the cache if cache() is set
uncache() - uncaches and returns object for chaining
setBounds(width||x||Boundary, height||y, null||width, null||height) - overrides CreateJS setBounds() and returns object for chaining
If you do not provide any parameters, then the bounds will be reset to the calculated bounds
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle - thanks Joseph Diefenbach
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
getBounds(targetSpace) - overrides CreateJS getBounds() and returns a rectangle with x, y, width height of bounds (not including outside of border)
pass in a Container (including Stage) to map rectangle to that coordinate space
childrenToBitmap() - turns content to a Bitmap and adds bitmap to container - removing all other children
sortBy(prop) - sorts the children of the container by a property - must be numeric
normalize(prop, from, from2, min, max, factor, clamp) - sets a ratio property (1 to 0) for each item in a Container.
passing in no parameters will normalize to the last normalized parameters - also see normalized property
** Supports ZIM DUO
PARAMETERS: prop - the property (as a string) to normalize
from - where the ratio will start at 1, values can be START (highest number), END (lowest number), CENTER, LEFT, RIGHT
from2 - used with "reg" with values of START, END, CENTER, TOP, BOTTOM - see the SPECIAL note down below.
min and max - can be set to override the calculated min and max values for the items in container - min and max are ignored for "reg"
factor - (default 1) is going the same direction and -1 is going in opposite direction
targetRound - (default false) set to true to round the converted number
clamp - (default true) set to false to let results go outside min and max range
WORKINGS: the ratio is 1 when it is closest to the from parameter(s) and 0 when farthest
For example, container.normalize("x") would provide a ratio property for each item in the container
with a default from START that would be 1-item.x/(largestX-smallestX)
In other words, if the item is the least distance in the x then ratio is 1, if the item is the most distance in the x then the ratio is 0
The from parameter will determine where the ratio is the largest.
container.normalize("x", END) would be 0 for an x of 0 and 1 for an item on the right side
container.normalize("x", CENTER) would be 1 for an item in the middle and 0 for items at the start and end
Set factor to -1 to reverse the direction of the ratio - eg. 0 in the middle and 1 at the start and end.
Or set min and max values to override the calculated min and max
The clamp, if true, will keep values between min and max or let them go outside these if false
there is one ratio property per object but this can be set and used any number of times.
NOTE: The ratio property is like a ZIM Proportion convert() but to each item in the container.
A provided property is converted based on a min and max to a target of 1 to 0 (factor is inverted)
SPECIAL: a property of "reg" will actually set the registration to the from value
the still property of reg() is used to keep the item from shifting.
An _orX and _orY will be provided on each item for original regX and regY.
setting normalize("reg", CENTER) will do both horizontal and vertical to the container dimensions.
If this is not desired, use container.loop(item=>{item.reg(item._orX, item._orY, true)});
to set the registration point back but still keep the ratio property
USAGE: the ratio property can be used by animate() with sequenceRate to set the rate of an animation based on ratio
Or the ratio property can be used directly - for instance, to set a scale based on a distance from somewhere
Or as another example, set the alpha based on the rotation of a shape in the container
specialColor(colorCommand, colorObject) - used internally by ZIM Shapes
to set GradientColor, RadialColor and BitmapColor on a fill or stroke color command
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - clones the container, its properties and all its children
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if a Container holds a new Circle(20,[blue,green])
then its clone might be blue or green
If exact is set to true then the clone will be whatever color was picked for the original circle
disposeAllChildren() - removes and disposes all children but leaves the container (see also CreateJS removeAllChildren() which does not dispose them)
dispose(disposing) - removes from parent, removes event listeners - must still set outside references to null for garbage collection
if calling dispose() on the super class from a custom class then pass in true to indicate already started dispose (otherwise infinite loops)
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
** common to all DisplayObjects that extend a Container such as ZIM Shapes and Components
type - holds the class name as a String
group - used when the object is made to add STYLE with the group selector (like a CSS class)
** bounds must be set first (or width and height parameters set) for these to work
** setting these adjusts scale not bounds and getting these uses the bounds dimension times the scale
width - gets or sets the width. Setting the width will scale the height to keep proportion (see widthOnly below)
height - gets or sets the height. Setting the height will scale the width to keep proportion (see heightOnly below)
widthOnly - gets or sets the width. This sets only the width and may change the aspect ratio of the object
heightOnly - gets or sets the height. This sets only the height and may change the aspect ratio of the object
ratio - get a ratio set by the Container normalize method() - or Tile itemRegX, itemRegY parameters
this will probably be a value from 1 to 0 as to how close the property is the end specified in the from parameter of normalize()
a value of 1 is the closest and a value of 0 is the farthest - see the normalize() method for details
normalized - get if the container has been normalized - see normalized parameter
draggable - set to true for a default drag() and false for a noDrag()
level - gets or sets the level of the object in its parent container (or the stage) - a property for parent.getChildIndex() and parent.setChildIndex()
depth - for ZIM VR - the depth used to shift left and right channel and for parallax in VR - also see dep() ZIM Display method
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
effects - an object that holds effects added such as blur, glow, shadow, color, multi and alpha - see effect() under ZIM Methods
** the following are convenience Effects that run a ZIM MultiEffect()
** these can use a lot of processing when animating - see Docs for effects()
** batch versions are available too as hueBatch, etc. these will not update the effect until updateEffects() is called on the object
hue - the tint of an object between -180 and 180 with 0 being no change
Also see the keyOut() method of Bitmap(), Pic() and SVG() that has a replacement color parameter
saturation - the amount of color of an object between -100 and 100 with 0 being no change
brightness - the lightness or darkness of an object between -255 and 255 with 0 being no change
contrast - the crispness of an object between -100 and 100 with 0 being no change
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scale, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
Shape
zim class - extends a createjs.Shape
DESCRIPTION
ZIM Shape lets you draw dynamic shapes beyond the ZIM provided shapes.
You make a new shape object and then draw in its graphics property
using similar commands to the HTML Canvas commands (and Flash Bitmap drawing).
See the CreateJS Easel Shapes and Graphics docs:
https://www.createjs.com/docs/easeljs/classes/Graphics.html
ALSO SEE: https://zimjs.com/docs.html?item=Generator for dynamically drawing into shapes like Processing (P5js)
ALSO SEE: https://zimjs.com/docs.html?item=Squiggle,Blob for odd shapes and user adjustable shapes
ALSO SEE: https://zimjs.com/docs.html?item=Pen for dynamic drawing of lines
ALSO SEE: https://zimjs.com/docs.html?item=Connectors for dynamic connections
// these mean we rarely use Shape directly but all of above were made in ZIM with Shape
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
NOTE
as of ZIM 10.6.0 the tiny API is available right on the Shape (no need for graphics)
EXAMPLE
// NEWER CODE
// Uses the tiny API (see options down below) right on the ZIM Shape
// for example: f() is fill() and dr() is drawRect()
// s() is beginStroke(), ss() is setStrokeStyle(), mt() is moveTo(), lt() is lineTo()
// draw a red rectangle into a shape
new Shape().f(red).dr(0,0,200,100).addTo();
// but it would be easier to use
// new Rectangle(200, 100, red).addTo();
// we can draw lines, etc. (but also see the ZIM Line object)
new Shape().s(blue).ss(5).mt(200,200).lt(300,300).addTo();
// note - we can draw as much as we want in the same shape
EXAMPLE
// OLDER CODE
// The first example uses a tiny API (see options below)
// The traditional full commands are available on the graphics object:
const shape = new Shape().addTo();
shape.graphics.beginFill(red).drawRect(0,0,200,100);
// or often we stored the graphics object in a variable g
const g = shape.graphics;
g.beginStroke(blue).moveTo(200,200).lineTo(300,300);
EXAMPLE
// to change a color or stroke after it has been made use command:
const shape = new Shape().addTo();
const strokeColor = shape.s(red).command;
shape.dr(50,50,100,100);
S.update();
timeout(1, ()=>{
strokeColor.style = blue;
S.update();
});
// This seems a little complex which is why ZIM provides many basic shapes
// Rectangle, Circle, Triangle, Squiggle, Blob, Poly, Line, Flare
// that can be adjusted dynamically with properties
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** Shape supports three different sets of parameters as follows:
a - (default null) - width and height equal to parameter a (x and y will be 0)
a, b - (default null) - the width and height (x and y will be 0)
a, b, c, d - (default null) - the x, y, width and height of the bounds
graphics - (default null) a CreateJS Graphics instance (see CreateJS docs)
or just use the graphics property of the shape object (like usual)
optimize - (default false) set to true to not store graphics methods directly on Shape
this means the shapes graphics property will need to be used to access f(), s(), ss(), etc.
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
The following shortcuts to CreateJS graphics methods are provided (as long as optimize is false)
See https://www.createjs.com/docs/easeljs/classes/Graphics.html for definitions and parameters
mt() moveTo
lt() lineTo
a() arc
at() arcTo
bt() bezierCurveTo
ct() curveTo
qt() quadraticCurveTo (same as curveTo)
r() rect
cp() closePath
c() clear
f() beginFill
lf() beginLinearGradientFill
rf() beginRadialGradientFill
bf() beginBitmapFill
ef() endFill
ss() setStrokeStyle
sd() setStrokeDash
s() beginStroke
ls() beginLinearGradientStroke
rs() beginRadialGradientStroke
bs() beginBitmapStroke
es() endStroke
dr() drawRect
rr() drawRoundRect
rc() drawRoundRectComplex
dc() drawCircle
de() drawEllipse
dp() drawPolyStar
pg() polygon // added in ZIM CreateJS 1.3.3 (Diamond)
p() decodePath
cache(width||x, height||y, null||width, null||height, scale, options, margin, rtl, willReadFrequently) - overrides CreateJS cache() and returns object for chaining
** Supports ZIM DUO
If you do not provide the first four parameters, then the cache dimensions will be set to the bounds of the object
width||x - (default getBounds().x) the width of the chache - or the x if first four parameters are provided
height||y - (default getBounds().y) the height of the chache - or the y if first four parameters are provided
width - (default getBounds().width) the width of the chache - or null if first two parameters are provided
height - (default getBounds().height) the height of the chache - or null if first two parameters are provided
scale - (default 1) set to 2 to cache with twice the fidelity if later scaling up
options - (default null) additional parameters for cache logic - see CreateJS somewhere for details
also added adjustBounds property for options - set to true to set new bounds and registration point
on cached objects with x,y,width,height different than the original
this appears to NOT be the default with createjs cache() which keeps the original registration point and bounds
automatically fixing this changes lots of things so use the adjustBounds option when needed
for instance when caching parts of a container and requiring hit tests or the part to be draggable, etc.
margin - (default 0) add or subtract a margin from the bounds
eg. margin:10 will make the cache size 10 pixels more on all sides
this can be handy when caching objects with borders - that go half outside the natural bounds
rtl - (default false) set to true to use right to left
willReadFrequently - (default null) set to true if planning on using operations with getImageData() or toDataURL()
if you get a warning in the console about willReadFrequently then set this to true
setBounds(width||x||Boundary, height||y, null||width, null||height) - overrides CreateJS setBounds() and returns object for chaining
If you do not provide any parameters, then the bounds will be reset to the calculated bounds
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle - thanks Joseph Diefenbach
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
getBounds(targetSpace) - overrides CreateJS getBounds() and returns a rectangle with x, y, width height of bounds (not including outside of border)
pass in a Container (including Stage) to map rectangle to that coordinate space
hasProp(property) - returns true if String property exists on object else returns false
clone(recursive) - makes a copy of the shape
recursive defaults to true so copy will have own copy of graphics
set recursive to false to have clone share graphic property
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), placeReg(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
command - save a previously chained operation as a command
then can use the command to change the operation later (see example above)
group - used when the object is made to add STYLE with the group selector (like a CSS class)
** bounds must be set first (or width and height parameters set) for these to work
** setting these adjusts scale not bounds and getting these uses the bounds dimension times the scale
width - gets or sets the width. Setting the width will scale the height to keep proportion (see widthOnly below)
height - gets or sets the height. Setting the height will scale the width to keep proportion (see heightOnly below)
widthOnly - gets or sets the width. This sets only the width and may change the aspect ratio of the object
heightOnly - gets or sets the height. This sets only the height and may change the aspect ratio of the object
draggable - set to true for a default drag() and false for a noDrag()
level - gets or sets the level of the object in its parent container (or the stage) - a property for parent.getChildIndex() and parent.setChildIndex()
depth - for ZIM VR - the depth used to shift left and right channel and for parallax in VR - also see dep() ZIM Display method
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
effects - an object that holds effects added such as blur, glow, shadow, color, multi and alpha - see effect() under ZIM Methods
** the following are convenience Effects that run a ZIM MultiEffect()
** these can use a lot of processing when animating - see Docs for effects()
** batch versions are available too as hueBatch, etc. these will not update the effect until updateEffects() is called on the object
hue - the tint of an object between -180 and 180 with 0 being no change
saturation - the amount of color of an object between -100 and 100 with 0 being no change
brightness - the lightness or darkness of an object between -255 and 255 with 0 being no change
contrast - the crispness of an object between -100 and 100 with 0 being no change
ALSO
see the CreateJS Easel Docs for Shape properties, such as:
graphics, x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, mouseEnabled, etc.
EVENTS
See the CreateJS Easel Docs for Shape events, such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
Bitmap
zim class - extends a createjs.Bitmap
DESCRIPTION
Makes a Bitmap object from an image source (image, video or canvas).
It is best to use the assets and path parameters of ZIM Frame or the loadAssets() method of Frame
to preload the image and then use the asset() method to access the Bitmap.
See the ZIM Frame class and asset example on the ZIM Frame page of templates.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Frame({ready, assets:"logo.jpg"});
function ready() {
const logo = new Pic("logo.jpg").center(); // logo is a Pic with a bitmap property that is a Bitmap
const logo2 = new Pic("logo.jpg").loc(100,100);
}
EXAMPLE
// turn a container of circles into a Bitmap
const circles = new Container(W, H).addTo();
loop(10, ()=>{
new Circle(rand(200), [pink,green,blue,yellow,purple], dark).center(circles).ble();
});
const pic = new Bitmap(circles).center().drag();
circles.removeFrom();
// previous to ZIM 10.8.0 we needed to use the cacheCanvas:
var pic = new Bitmap(circles.cache().cacheCanvas).center().drag();
EXAMPLE
// fill a Bitmap with noise:
const noise = new Noise();
// empty Bitmap size 200, 200
const bmp = new Bitmap(null,200,200).center();
// we fill the bitmap starting from top left going across in the inner loop,
// then down, then across, etc. until we get to bottom right.
const f = 50; // used to make noise bigger or smaller - see the blob comment below
for (let y = 0; y < bmp.height; y++) {
for (let x = 0; x < bmp.width; x++) {
// the noise methods return a number from -1 to 1
// by adding 1 we get a number between 0 and 2 then divide by 2
// and we multiply this by 255 to get a number between 0 and 255
let value = (noise.simplex2D(x, y)+1)/2 * 255;
// or get blobs by smoothing and adjusting frequency:
// var value = smoothStep((noise.simplex2D(x/f, y/f)+1)/2, .3,.35) * 255;
// imageData is four values per pixel
// the red, green, blue and alpha
// in one big long array - each value will be constrained to between 0 and 255
// this i value will increase by 4 each time
// then we write the same value for red, green, blue to get a shade of grey
let i = (x + y * bmp.width) * 4;
bmp.imageData.data[i] = value; // red (0-255)
bmp.imageData.data[i + 1] = value; // green (0-255)
bmp.imageData.data[i + 2] = value; // blue (0-255)
bmp.imageData.data[i + 3] = 255; // alpha (0-255)
}
}
bmp.drawImageData();
EXAMPLE
// applying filters
new Pic("statue.jpg").effect(new BlurEffect()).center();
EXAMPLE
// getting the color at point(100, 100) on the Bitmap
const bitmap = new Bitmap(new Pic("statue.jpg"));
zog(bitmap.getColorAt(100,100)); // rgba(245,142,37,1)
EXAMPLE
// a Base64 image - with a long list of characters:
const image = "data:image/png;base64,longlistofcharacters";
const logo;
Bitmap.fromData(image, bitmap=>{
logo = bitmap.center();
S.update();
});
EXAMPLE
const thumbs = [];
const cols = 5;
const rows = 5;
const image = asset("yourimage.jpg");
const w = image.width/cols;
const h = image.height/cols;
loop(rows, r=>{
loop(cols, c=>{
// make Bitmap show a different part of the main image each time
// note: width, height, left, top
// NOT x, y, width, height like Container
// left and top specifiy where in an image
// to start the picture at 0,0 in the Bitmap
thumbs.push(new Bitmap(image, w, h, c*w, r*h));
});
});
const tile = new Tile(thumbs, cols, rows, 0, 0, true).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
image - an HTML image URL (may not load right away - see Frame loadAssets)
or as of 10.8.0 a DisplayObject - this will be turned into a cacheCanvas
and then the DisplayObject turned back to its previous cached setting
width - (default image width or 100) the width of the resulting Bitmap - will potentially crop an image
see also height, left and top parameters
which allow part of an image to be drawn into the Bitmap
and is handy rather than masking to cut up an image into squares for instance
height - (default image height or 100) the height of the resulting Bitmap
left - (default 0) where on the source image to start the left of the image
top - (default 0) where on the source image to start the top of the image
scale - if making a Bitmap from a DisplayObject, this will scale the object before it is cached for better resolution
the resulting bitmap will be the scaled size
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
keyOut(color, tolerance, replacement) - remove color from Bitmap and a tolerance between 0-1
the default color is "#389b26" which is a medium dark green
the default tolerance is .1 - the higher the tolerance the less sensitive the keying process - so more colors will be removed similar to the provided color
color and tolerance can be an array of colors and tolerances (or just one tolerance if all are the same)
replacement (default clear) a color to replace the keyed out color with or an optional array to match the colors array if an array is used
fromData(data, callback) - STATIC method so use the Bitmap class directly: Bitmap.fromData()
The callback will receive a reference to the Bitmap after 50ms or 100ms.
There is no event for making a Bitmap from base64 for instance - so this will have to do.
drawImageData(x, y, sourceX, sourceY, sourceWidth, sourceHeight) - draws the Bitmap's imageData data to the Bitmap
NOTE: This is only used when dynamically drawing a Bitmap with data - not for your normal picture
See the imageData property which should be set before using the drawImageData() method
ZIM calls a putImageData method for the HTML Canvas and then transfers this to the Bitmap
See also https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData - but let ZIM do the work...
Usually just leave the parameters blank
x - (default 0) where to start putting the drawing in the x
y - (default 0) where to start putting the drawing in the y
sourceX - (default 0) where in the imageData to start using the data in the x
sourceY - (default 0) where in the imageData to start using the data in the y
sourceWidth - (default the width of the imageData) how much width of the data to use
sourceHeight - (default the height of the imageData) how much height of the data to use
setBounds(width||x||Boundary, height||y, null||width, null||height) - overrides CreateJS setBounds() and returns object for chaining
If you do not provide any parameters, then the bounds will be reset to the calculated bounds
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle - thanks Joseph Diefenbach
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
getBounds(targetSpace) - overrides CreateJS getBounds() and returns a rectangle with x, y, width height of bounds (not including outside of border)
pass in a Container (including Stage) to map rectangle to that coordinate space
cache(width||x, height||y, null||width, null||height, scale, options, rtl, willReadFrequently) - overrides CreateJS cache() and returns object for chaining
** Supports ZIM DUO
** Usually you do not want to cache a Bitmap as it is already a Bitmap ;-)
** But for applying a filter or using a cacheCanvas to get a context, etc. then you might.
If you do not provide the first four parameters, then the cache dimensions will be set to the bounds of the object
width||x - (default getBounds().x) the width of the chache - or the x if first four parameters are provided
height||y - (default getBounds().y) the height of the chache - or the y if first four parameters are provided
width - (default getBounds().width) the width of the chache - or null if first two parameters are provided
height - (default getBounds().height) the height of the chache - or null if first two parameters are provided
scale - (default 1) set to 2 to cache with twice the fidelity if later scaling up
options - (default null) additional parameters for cache logic - see CreateJS somewhere for details
also added adjustBounds property for options - set to true to set new bounds and registration point
on cached objects with x,y,width,height different than the original
this appears to NOT be the default with createjs cache() which keeps the original registration point and bounds
automatically fixing this changes lots of things so use the adjustBounds option when needed
for instance when caching parts of a container and requiring hit tests or the part to be draggable, etc.
rtl - (default null) set to true to use Right to Left.
willReadFrequently - (default null) set to true if planning on using operations with getImageData() or toDataURL()
if you get a warning in the console about willReadFrequently then set this to true
getColorAt(x,y,array) - returns the rgba() value at the x and y location - passes array of [r,g,b,a] if array parameter is true
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied - also copies file and src properties
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
if this is a cloned bitmap then the original asset("image.png") will still exist unless it is disposed.
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Bitmap methods, such as:
on(), off(), dispatchEvent(), etc.
PROPERTIES
type - holds the class name as a String
file - if loaded as an asset this is the file name
imageData - data for the pixels stored in a data property of an ImageData object
NOTE: This is only used when dynamically drawing a Bitmap with data - not for your normal picture
The data property is an one dimensional Array with consecutive red, green, blue, alpha values (0-255) for each pixels
eg. 0,0,0,255,255,255,255,255 is a black pixel with 1 alpha and a white pixel with 1 alpha
You set this before calling the Bitmap drawImageData() method
See also https://developer.mozilla.org/en-US/docs/Web/API/ImageData - but let ZIM do the work
group - used when the object is made to add STYLE with the group selector (like a CSS class)
** bounds must be set first (or width and height parameters set) for these to work
** setting these adjusts scale not bounds and getting these uses the bounds dimension times the scale
width - gets or sets the width. Setting the width will scale the height to keep proportion (see widthOnly below)
height - gets or sets the height. Setting the height will scale the width to keep proportion (see heightOnly below)
widthOnly - gets or sets the width. This sets only the width and may change the aspect ratio of the object
heightOnly - gets or sets the height. This sets only the height and may change the aspect ratio of the object
draggable - set to true for a default drag() and false for a noDrag()
level - gets or sets the level of the object in its parent container (or the stage) - a property for parent.getChildIndex() and parent.setChildIndex()
depth - for ZIM VR - the depth used to shift left and right channel and for parallax in VR - also see dep() ZIM Display method
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
effects - an object that holds effects added such as blur, glow, shadow, color, multi and alpha - see effect() under ZIM Methods
** the following are convenience Effects that run a ZIM MultiEffect()
** these can use a lot of processing when animating - see Docs for effects()
** batch versions are available too as hueBatch, etc. these will not update the effect until updateEffects() is called on the object
hue - the tint of an object between -180 and 180 with 0 being no change
saturation - the amount of color of an object between -100 and 100 with 0 being no change
brightness - the lightness or darkness of an object between -255 and 255 with 0 being no change
contrast - the crispness of an object between -100 and 100 with 0 being no change
ALSO
see the CreateJS Easel Docs for Bitmap properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, mouseEnabled, etc.
EVENTS
See the CreateJS Easel Docs for Bitmap events, such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS
// boom.png is a sprite sheet found online
// It has 8 columns and 6 rows that we can visually count
// We can enter a total parameter if it does not end evenly in the grid
// A graphics editor (like Photoshop) could be used to see
// if there is an offset or spacing, etc. and enter those as parameters
// In this case, we do not need to do any of this - just enter the cols and rows
new Frame(FIT, 1024, 768, black, darker, ready, "boom.png", "https://zimjs.org/assets/");
function ready() {
const animation = new Sprite({
image:"boom.png",
cols:8,
rows:6,
animations:{mid:[10,20], end:[30,40]} // optional animations with labels
// see CreateJS SpriteSheet docs for the various animation format as there are a few different ones!
})
.center()
.run(2); // plays the frames of the Sprite over 2 seconds (master time)
// OR use the label to play the frames listed in animations parameter
animation.run(1, "mid");
// OR run a series of animations
// by passing an array of label objects to the label parameter
// these each have a time so the master time is ignored
// they can also have any of the run() parameters
// if you provide an array of labels, you cannot rewind the overall animation
animation.run(null, [
{label:"mid", time:1},
{label:"end", time:.5, loop:true, loopCount:5, call:function(){zog("loops done");}},
{startFrame:10, endFrame:20, time:1}
]);
// OR can call a function when done
animation.run(1, "mid", function(){
S.removeChild(animation);
S.update();
});
// OR can loop the animation
animation.run({time:2, loop:true}); // see run() parameters for more
}
EXAMPLE
// using Sprite as a texture atlas - or spritesheet of different images
// see: https://zimjs.com/zapp/Z_FDJXA
// load in assets and path
new Frame({ready, assets:["fruit.png", "fruit.json"], path:"assets/"});
function ready() {
new Sprite({json:"fruit.json", label:"apple"}).center();
}
EXAMPLE
// Here is an example with CreateJS SpriteSheet data
// robot.png is a sprite sheet made by ZOE based on a Flash swf
// you can also make your own with Photoshop or Texture Packer
F.loadAssets("robot.png");
F.on("complete", ()=>{
// using ZOE to export swf animation to spritesheet data
// spritesheet data uses the image name, not the Bitmap itself
const image = new Pic("robot.png").image;
const spriteData = {
"framerate":24,
"images":[image],
"frames":[[0, 0, 256, 256, 0, -54, -10], many more - etc.],
"animations":{}
};
const animation = new Sprite({json:spriteData});
animation.center();
animation.run(2); // note, duration alternative to framerate
});
// OR
// load in data from external JSON
F.loadAssets(["robot.json", "robot.png"]);
// ... same as before
const animation = new Sprite({json:"robot.json"});
// ... same as before
// see CreateJS SpriteSheet docs for the format of the JSON file
// including various animation formats
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
image - the ZIM Pic() ir ZIM Bitmap() for the spritesheet
or use a string filename to a preloaded image file (in Frame or loadAssets())
cols - (default 1) - the columns in the spritesheet
rows - (default 1) the rows in the spritesheet
count - (default cols*rows) how many total frames in the spritesheet
offsetX - (default 0) the pixels from the left edge to the frames
offsetY - (default 0) the pixels from the top edge to the frames
spacingX - (default 0) the horizontal spacing between the frames
spacingY - (default 0) the vertical spacing between the frames
width - (default image width) the width including offset and spacing for frames
height - (default image height) the height including offset and spacing for frames
animations - (default null) an object literal of labels holding frames to play
{label:3, another:[4,10]}
run(1, "label") would play frame 3 for a second
run(1, "another") would play frames 4 to 10 for a second
{unordered:{frames:[1,2,3,22,23,24,"anotherLabel",5,6], next:prevLabel}}
There are also ways to set speeds - but would recommend dividing into simple labels
and using the label series technique available with the run() method
json - (default null) a JSON string for a CreateJS SpriteSheet
or use a string filename to a preloaded JSON file (in Frame or loadAssets())
If you pass in a json parameter, all other parameters are ignored
NOTE: remember that JSON needs quotes around the animation properties above:
{"label":3, "another":[4,10]}
JSON hash and JSON array formats from TexturePacker are supported as well as the createjs/easeljs format
See https://www.codeandweb.com/free-sprite-sheet-packer for instance
id - (default randomly assigned) an id you can use in other animations - available as sprite.id
use this id in other animations for pauseRun and stopRun to act on these as well
globalControl - (default true) pauseRun and stopRun will control other animations with same id
spriteSheet - (default null) pass in a CreateJS SpriteSheet to build a Sprite from that
label - (default null) pass in a label to stop on initially - to play from a label use the run({label:val}) method
frame - (default zimDefaultFrame) specify a Frame other than the default frame
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
run(time, label, call, params, wait, waitedCall, waitedParams, loop, loopCount, loopWait, loopCall, loopParams, loopWaitCall, loopWaitParams, loopPick, rewind, rewindWait, rewindCall, rewindParams, rewindWaitCall, rewindWaitParams, rewindTime, rewindEase, startFrame, endFrame, tweek, id, globalControl)
The run() method animates the Sprite over an amount of time
Would recommend this method over the CreateJS play() and gotoAndPlay()
methods because the framerate for these get overwritten by other S.update() calls
With run() you get other nice ZIM animate features as well as follows:
Returns the object for chaining
Can be paused with pauseAnimate(true) or unpaused with pauseAnimate(false)
Can be stopped with stopAnimate() on the Sprite
supports DUO - parameters or single object with properties below
time (default 1) - the time in seconds to run the animations (the master time)
label (default null) - a label specified in the Sprite animations parameter
if this is an array holding label objects for example:
[{label:"run", time:1}, {label:"stand", time:2}]
then the sprite will play the series with the times given and ignore the master time
Note: if any of the series has a loop and loops forever (a loopCount of 0 or no loopCount)
then this will be the last of the series to run
rewind is not available on the outside series but is available on an inside series
call - (default null) the function to call when the animation is done
params - (default target) a single parameter for the call function (eg. use object literal or array)
wait - (default 0) seconds to wait before doing animation
waitedCall - (default null) call the function after a wait time if there is one
waitedParams - (default null) parameters to pass to the waitedCall function
loop - (default false) set to true to loop animation
loopCount - (default 0) if loop is true how many times it will loop (0 is forever)
loopWait - (default 0) seconds to wait before looping (post animation wait)
loopCall - (default null) calls function after loop and loopWait (not including last loop)
loopParams - (default target) parameters to send loopCall function
loopWaitCall - (default null) calls function after at the start of loopWait
loopWaitParams - (default target) parameters to send loopWaitCall function
rewind - (default false) set to true to rewind (reverse) animation (doubles animation time) (not available on label series)
rewindWait (default 0) seconds to wait in the middle of the rewind
rewindCall (default null) calls function at middle of rewind after rewindWait
rewindParams - (default target) parameters to send rewindCall function
rewindWaitCall (default null) calls function at middle of rewind before rewindWait
rewindWaitParams - (default target) parameters to send rewindCall function
rewindTime - (default time) set to a time in seconds to adjust the time to rewind
rewindEase - (default null) see ease parameter for options for rewind ease
note - this goes backwards - so "bounceOut" would happen at the end of the rewind
startFrame - (default null - or 0) the frame to start on - will be overridden by a label with frames
endFrame - (default null - or totalFrames) the frame to end on - will be overridden by a label with frames
tweek - (default 1) a factor for extra time on rewind and loops if needed
id - (default randomly assigned) an id you can use in other animations - available as sprite.id
use this id in other animations for pauseRun and stopRun to act on these as well
globalControl - (default true) pauseRun and stopRun will control other animations with same id
pauseOnBlur - (default true) pause the sprite when the window is not seen or set to false to keep playing the sprite
pauseRun(state) - pause or unpause the animation (including an animation series)
state - (default true) when true the animation is paused - set to false to unpause
returns object for chaining
stopRun() - stop the sprite from animating
setBounds(width||x||Boundary, height||y, null||width, null||height) - overrides CreateJS setBounds() and returns object for chaining
If you do not provide any parameters, then the bounds will be reset to the calculated bounds
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle - thanks Joseph Diefenbach
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
getBounds(targetSpace) - overrides CreateJS getBounds() and returns a rectangle with x, y, width height of bounds (not including outside of border)
pass in a Container (including Stage) to map rectangle to that coordinate space
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Sprite methods, such as:
play(), gotoAndPlay(), gotoAndStop(), stop(), advance(),
on(), off(), dispatchEvent(), etc.
PROPERTIES
type - holds the class name as a String
id - an id that you can use in other animations to also be controlled by pauseRun() and stopRun()
frame - get and set the current frame of the Sprite
normalizedFrame - if animations have CreateJS speeds applied, zim handles these by making extra frames
for example, if a speed is given of .5 then two frames are made (min resulution is .1)
normalizedFrames - an array of total frames after being normalized - really for internal usage
totalFrames - get the total frames of the Sprite - read only
animations - the animations data with labels of frames to animate
running - is the sprite animation being run (includes both paused and unpaused) - read only
runPaused - is the sprite animation paused (also returns paused if not running) - read only
note: this only syncs to pauseRun() and stopRun() not pauseAnimate() and stopAnimate()
note: CreateJS has paused, etc. but use that only if running the CreateJS methods
such as gotoAndPlay(), gotoAndStop(), play(), stop()
draggable - set to true for a default drag() and false for a noDrag()
group - used when the object is made to add STYLE with the group selector (like a CSS class)
** bounds must be set first (or width and height parameters set) for these to work
** setting these adjusts scale not bounds and getting these uses the bounds dimension times the scale
width - gets or sets the width. Setting the width will scale the height to keep proportion (see widthOnly below)
height - gets or sets the height. Setting the height will scale the width to keep proportion (see heightOnly below)
widthOnly - gets or sets the width. This sets only the width and may change the aspect ratio of the object
heightOnly - gets or sets the height. This sets only the height and may change the aspect ratio of the object
draggable - set to true for a default drag() and false for a noDrag()
level - gets or sets the level of the object in its parent container (or the stage) - a property for parent.getChildIndex() and parent.setChildIndex()
depth - for ZIM VR - the depth used to shift left and right channel and for parallax in VR - also see dep() ZIM Display method
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
effects - an object that holds effects added such as blur, glow, shadow, color, multi and alpha - see effect() under ZIM Methods
** the following are convenience Effects that run a ZIM MultiEffect()
** these can use a lot of processing when animating - see Docs for effects()
** batch versions are available too as hueBatch, etc. these will not update the effect until updateEffects() is called on the object
hue - the tint of an object between -180 and 180 with 0 being no change
saturation - the amount of color of an object between -100 and 100 with 0 being no change
brightness - the lightness or darkness of an object between -255 and 255 with 0 being no change
contrast - the crispness of an object between -100 and 100 with 0 being no change
ALSO
see the CreateJS Easel Docs for Sprite properties, such as:
currentFrame, framerate, paused, currentAnimation, currentAnimationFrame, spriteSheet,
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, mouseEnabled, etc.
EVENTS
See the CreateJS Easel Docs for Sprite events, such as:
animationend, change, added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
MovieClip
zim class - extends a createjs.MovieClip
DESCRIPTION
A MovieClip adds timelines to a Container.
The timelines are animate() zimTween properties.
The zimTween property returns a CreateJS Tween object.
Primarily made to support Adobe Animate MovieClip export.
*Consider this experimental for the moment...
NOTE
to use animate() on a MovieClip, add the MovieClip to a Container and animate() the Container
otherwise the animate() may advance the MovieClip.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const movieClip = new MovieClip();
const circle = new Circle(20, blue).animate({
props:{scale:3}, time:.1, rewind:true, loop:true
});
// Time is in frames NOT in ms - so 100 frames at the Ticker.framerate 60 fps by default is almost 2 seconds
// To change the Ticker's framerate use setFPS(mobile, desktop) method
// If you use one number then both mobile and desktop are set to that fps.
// The defaults are 60 fps mobile (as of ZIM Cat 04) and 60 fps desktop
movieClip.timeline.addTween(circle.zimTween);
movieClip.play();
movieClip.center();
S.on("stagemousedown", ()=>{
movieClip.paused = !movieClip.paused;
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
// from the CreateJS MovieClip docs: https://www.createjs.com/docs/easeljs/classes/MovieClip.html
mode - (default "independent") or single_frame (based on startPosition) or synched (syncs to parent)
startPosition - (default 0) the start position of the MovieClip (*could not get to work)
loop - (default true) set to false not to loop (*did not seem to loop so use loop:true in zim.animate())
labels - (default null) declare label property with position value
eg. {explode:20} to use with gotoAndPlay("explode") rather than gotoAndPlay(20)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
setBounds(width||x||Boundary, height||y, null||width, null||height) - overrides CreateJS setBounds() and returns object for chaining
If you do not provide any parameters, then the bounds will be reset to the calculated bounds
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle - thanks Joseph Diefenbach
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
getBounds(targetSpace) - overrides CreateJS getBounds() and returns a rectangle with x, y, width height of bounds (not including outside of border)
pass in a Container (including Stage) to map rectangle to that coordinate space
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for MovieClip methods, such as:
play(), gotoAndPlay(), gotoAndStop(), stop(), advance(),
on(), off(), dispatchEvent(), etc.
PROPERTIES
type - holds the class name as a String
draggable - set to true for a default drag() and false for a noDrag()
group - used when the object is made to add STYLE with the group selector (like a CSS class)
** bounds must be set first (or width and height parameters set) for these to work
** setting these adjusts scale not bounds and getting these uses the bounds dimension times the scale
width - gets or sets the width. Setting the width will scale the height to keep proportion (see widthOnly below)
height - gets or sets the height. Setting the height will scale the width to keep proportion (see heightOnly below)
widthOnly - gets or sets the width. This sets only the width and may change the aspect ratio of the object
heightOnly - gets or sets the height. This sets only the height and may change the aspect ratio of the object
draggable - set to true for a default drag() and false for a noDrag()
level - gets or sets the level of the object in its parent container (or the stage) - a property for parent.getChildIndex() and parent.setChildIndex()
depth - for ZIM VR - the depth used to shift left and right channel and for parallax in VR - also see dep() ZIM Display method
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
effects - an object that holds effects added such as blur, glow, shadow, color, multi and alpha - see effect() under ZIM Methods
** the following are convenience Effects that run a ZIM MultiEffect()
** these can use a lot of processing when animating - see Docs for effects()
** batch versions are available too as hueBatch, etc. these will not update the effect until updateEffects() is called on the object
hue - the tint of an object between -180 and 180 with 0 being no change
saturation - the amount of color of an object between -100 and 100 with 0 being no change
brightness - the lightness or darkness of an object between -255 and 255 with 0 being no change
contrast - the crispness of an object between -100 and 100 with 0 being no change
ALSO
see the CreateJS Easel Docs for MovieClip properties, such as:
currentFrame, totalFrames, currentLabel, duration, framerate, labels, loop, mode, paused, startPosition, timeline,
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, mouseEnabled, parent, etc.
EVENTS
See the CreateJS Easel Docs for MovieClip events, such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
SVGContainer
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Parses SVG and adds items to a ZIM Container.
Items are created as ZIM Shapes: Circle, Rectangle, Blob, Squiggle.
If geometric is true then Circle and Rectangle are used otherwise Blob is used.
Items can be accessed using svgcontainer.getChildAt(0), etc.
See: https://zimjs.com/svg/
See: https://zimjs.com/explore/svgcontainer.htmlALSO
see SVG() class under Frame module.
An SVG path string can be passed directly to a Squiggle or Blob points parameter
and so avoiding the SVGContainer - see ZIM Squiggle and Blob
WARNING: this should be considered experimental
The idea is that paths from SVG can be made editable in ZIM
or animation, dragging, or Label along paths can be accommodated
As such, not all SVG features will work - no CSS, Text, Gradients, DropShadows, etc.
It is possible that these will be added at some point
See also the ZIM svgToBitmap() function under META to get an exact image of the SVG
Thank you https://github.com/colinmeinke/svg-arc-to-cubic-bezier for the Arc conversion
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const svgContainer = new SVGContainer(asset("sample.svg")).addTo();
// OR
const svg = `<svg width="150" height="200" xmlns="h t t p ://www.w3.org/2000/svg">
<path id="lineAB" d="M 0 0 l 150 200" stroke="red" stroke-width="3" fill="none" />
</svg>`;
const svgContainer = new SVGContainer(svg).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
svg - an SVG file loaded into an asset() or SVG text
splitTypes - (default false) - set to true to split different types of paths into separate objects
geometric - (default true) - set to false to load Rectangle and Circle objects as Blob objects
showControls - (default true) set to false to start with controls not showing
interactive - (default true) set to false to turn off controls, move, toggle, select, edit - leaving just the shapes
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
processPath(path) - path is an SVG path string - returns a ZIM Blob or Squiggle points array
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
svg - a reference to the SVG text
type - holds the class name as a String
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊
Tag
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Creates a <div></div> with id of id and overlays it on the Canvas with the createjs DOMElement
The tag is scaled and positioned with ZIM code and can be filled with any HTML desired
Access to the HTML tag is provided with the tag property (so you can use innerHTML or style on this)
However a convenience innerHTML and style properties have been added to Tag
CSS Styles can be applied to the HTML tag as with any HTML div tag
Or use the chainable add() method to add a String of HTML (instead of setting innerHTML)
SEE: https://zimjs.com/explore/tag.htmlNOTE
due to the HTML tag being overlayed, the tag.resize() must be called if it is manually scaled or moved
(This is called automatically when the stage is resized)
NOTE
if the tag is placed in a container and the container is removed or added again
the tag must be manually removed or added again with tag.removeFrom() or tag.addTo().
This is so ZIM does not have to keep track of HTML tags each time a container is added or removed.
NOTE
rotation and skewing of Tag is not supported - although might work with custom CSS transformations
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const tag = new Tag(300, 60).center().add("<h1>TITLE TEXT</h1>");
tag.style.color = red;
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 250) the width of the div tag
height - (default 70) the height of the div tag
Note: to set scrollBars use CSS: tag.style.overflow = "auto";
id - (default zimTag_randomNumber) a string id for the HTML div tag.
frame - (default the zdf) a reference to the Frame (to scale and position the HTML tag)
backgroundColor - (default "rgba(0,0,0,0)") a ZIM Rectangle used as a background
padding - (default 10) inner padding between edge of background rectangle and HTML tag
paddingH - (default padding) inner horizontal padding between edge of background rectangle and HTML tag
paddingV - (default padding) inner vertical padding between edge of background rectangle and HTML tag
expand - (default 20) hit area around background to count as a press on Tag - handy for dragging as HTML tag area will override mouse on canvas
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(htmlString) - chainable method to add HTML to tag - calling add() again will append
see innerHTML property as alternative or to overwrite the innerHTML
resize(update) - call the resize event if the scale or position of the tag is changed
this will sync the location of the div tag
resize() is only needed if the scale or x, y of the tag (or its container) is changed
it is not needed for general window resizing - the Tag handles this
Note: if the Frame itself changes location in the HTML document, call a F.update()
this will then dispatch an update event to the Tag and it will resize()
this is not needed if resizing the window or scrolling - see Frame update() method docs
update defaults to true - set to false to not update the stage during a resize()
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
tagID - the assigned id of the tag
tag - the HTML div tag - just a regular HMTL div tag which can be styled
innerHTML - the innerHTML property of the tag (so myTag.tag.innerHTML is not needed)
background - access to the ZIM Rectangle used as the background
frame - get or set the frame - set this if changing frames
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS: See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Shader
zim class - extends a zim.Bitmap which extends a createjs.Bitmap
DESCRIPTION
Makes a Bitmap from shader code. The Bitmap will update automatically if set to dynamic (default).
Shaders run on the GPU and are very fast for cool visual effects and are also the basis for 3D.
For 3D, we recommend using three.js with ZIM and the the Three helper module - overlayed or with TextureActive.
BUT - shaders are also commonly used for amazing 2D effects.
Also see ShaderOverlay() that overlays the raw WebGL Canvas on ZIM as a Tag() rather than converting to a Bitmap.
The best way to see what shaders are about are to look at the many examples on ShaderToy, for instance:
https://www.shadertoy.com
Many of the shaders from ShaderToy will work in ZIM Shader() with a simple cut and paste.
However, ones with multiple channels are currently not supported - but you may be able to add equivilant code.
For instance, a picture can be brought into the shader rather than using a channel.
There are many more shaders other than in ShaderToy.
Shaders have their own coding language called GLSL https://en.wikipedia.org/wiki/OpenGL_Shading_Language
ZIM Shader was built for OpenGL 3.0 but other versions may work.
This is a very complicated coding world based on C - so do not expect to easily make shaders.
Most likely, you will start with copying and perhaps modifying code - but it is not easy.
When looking at reference materials, note that ZIM has greatly simplified the requirements
So tend to ignore how shaders are set up to run
and concentrate on the actual fragment (and sometimes vertex) shader code
https://learnopengl.com/Getting-started/Shadershttps://thebookofshaders.com/https://thebookofshaders.com/glossary/
ZIM Shader() abstracts a couple hundred lines of somewhat famously complicated WebGL code.
There are three main inputs (beyond width and height)
FRAGMENT
Shader code that changes the pixel colors.
This is the code that is displayed in ShaderToy and is most popular in 2D shaders.
Fragment shaders run after Vertex shaders but it is an early parameter because the Vertex shader is usually default.
UNIFORMS
These are variables that we pass in to the shader.
ZIM provides a Uniforms() object for this purpose for easy animate() and wiggle() and component interactivity.
The uniforms will automatically be updated by ZIM Shader.
The following code will get inserted at the top of the shader code:
#version 300 es // version number - see versions parameter
precision mediump float; // can reset a different precision if desired
uniform vec3 iResolution; // width and height of shader (in pixels)
uniform float iTime; // shader playback time (in seconds)
uniform float iTimeDelta; // render time (in seconds)
uniform float iFrameRate; // shader frame rate (frames per second)
uniform int iFrame; // shader playback frame
uniform vec4 iMouse; // mouse coordinates x, y (in pixels), down (0/1), click (0/1)
uniform vec4 iDate; // year (full), month (0-11), day, time (in seconds from midnight)
uniform float iChange; // increases with the rate (parameter or property) of the Shader
VERTEX
Shader code that changes the verticies (points) of triangles.
This defaults to two triangles in a strip that make a rectangle based on the provided width and height.
This code will probably not be needed and is not shown in ShaderToy - but can be used in ZIM Shader()
TIPS
In the shader code, data types matter, are declared and need to match properly - for example:
float num = 1.0;
int count = 1;
vec2 size = vec(0.0, 1.0);
Vectors are used a lot and can have 2, 3, or 4 components (like array elements) that we access with x, y, z, w (or rgba or stpq)
These can be accessed and adjusted in multiple ways - called "swizzling" (examples from learnopengl.com)
vec2 someVec; // has two components
vec4 differentVec = someVec.xyxx; // make 4 components from the two components - repeating is fine
vec3 anotherVec = differentVec.zyw; // has three components
vec4 otherVec = someVec.xxxx + anotherVec.yxzy; // added components together
vec2 vect = vec2(0.5, 0.7); // two components - use leading 0 and trailing 0 to keep as float if desired
vec4 result = vec4(vect, 0.0, 0.0); // vect will be spread across the first two components
vec4 otherResult = vec4(result.xyz, 1.0); // first three components of results are spread across otherResult
ShaderToy uses a slightly different format which is converted by ZIM - see the Docs under fragment parameter.
A main thing to watch out for is that ShaderToy fragCoord is a vec2
whereas gl_FragCoord (WebGL 1.0) is a vec3 so use gl_FragCoord.xy to match fragCoord
Conditionals are often avoided for performance https://theorangeduck.com/page/avoiding-shader-conditionals
ZIM Shader() defaults to dynamic which means that it will update.
Set the dynamic parameter to false if the shader does not need to update.
SEE: https://zimjs.com/016/shaders for a mini-site of shaders in ZIM.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// A simple horizontal gradient shown four ways
// These four ways can be used throughout the examples
// but we will show the rest as the ShaderToy format.
// https://www.shadertoy.com/view/MlK3DK
// iResolution is a default uniform (see Uniforms above)
// VERSION 1 - ShaderToy mainImage(out, in) {} Format
const fragment = `
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
fragColor = mix(vec4(1,1,0,1), vec4(0,1,1,1), fragCoord.x/iResolution.x);
}
`;
new Shader(W, H, fragment).center();
// VERSION 2 - main() {} - traditional GLSL 3 format
const fragment = `
out vec4 fragColor;
void main() {
vec2 fragCoord = gl_FragCoord.xy; // convert default input vec3 gl_FragCoord to vec2 fragCoord
fragColor = mix(vec4(1,1,0,1), vec4(0,1,1,1), fragCoord.x/iResolution.x);
}
`;
new Shader(W, H, fragment).center();
// VERSION 3 - using gl_FragCoord directly
const fragment = `
out vec4 fragColor;
void main() {
fragColor = mix(vec4(1,1,0,1), vec4(0,1,1,1), gl_FragCoord.x/iResolution.x);
}
`;
new Shader(W, H, fragment).center();
// VERSION 4 - traditional GLSL 1 format (note version param in Shader)
const fragment = `
void main() {
gl_FragColor = mix(vec4(1,1,0,1), vec4(0,1,1,1), gl_FragCoord.x/iResolution.x);
}
`;
new Shader({width:W, height:H, fragment:fragment, version:""}).center();
EXAMPLE
// Animating with the iTime uniform (see default uniforms)
const fragment = `
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
vec2 uv = fragCoord.xy / iResolution.xy;
vec3 color = 0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0,2,4));
fragColor = vec4(vec3(color), 1.0);
}
`;
new Shader(W, H, fragment).center();
EXAMPLE
// https://zimjs.com/016/shader/spiral.html
// loading shader from file - often a glsl extension
// VS Code has a glsl-literal extension that will color syntax shader code
new Frame(FILL, 1024, 768, purple, black, ready, "spiral.glsl");
function ready() {
new Shader(W, H, asset("spiral.glsl")).addTo();
}
EXAMPLE
// A circle - using rgb() and circle() functions
const fragment = `
// center will be wiggled outside in ZIM so need a uniform
uniform vec2 center;
// prepare a function to convert RGB 0-255 to 0-1
vec3 rgb(float r, float g, float b) {
return vec3(r/255.0, g/255.0, b/255.0); // 0-1
}
// prepare a function to see if each point (uv) is inside or outside radius
// from wherever the center of the circle is located (pos - based on center uniform)
vec4 circle(vec2 uv, vec2 pos, float rad, vec3 color) {
float d = length(pos - uv) - rad;
float t = clamp(d, 0.0, 1.0); // threshhold 0 if within radius range from center
return vec4(color, 1.0 - t); // alpha 0 if outside radius
}
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
// circle will be 1/2 the height
float radius = 0.25 * iResolution.y;
// Background
vec4 layer1 = vec4(rgb(255.0, 165.0, 0.0), 1.0);
// Circle
vec3 red = rgb(255.0, 0.0, 0.0);
vec4 layer2 = circle(fragCoord.xy, center, radius, red);
// Blend the two using the alpha of the circle
fragColor = mix(layer1, layer2, layer2.a);
}
`;
const width = 500;
const height = 500;
const uniforms = {
center:[width/2, height/2]
};
const u = new Uniforms(uniforms).wiggle("center_A", width/2, 50,100, 2,4);
new Shader(width, height, fragment, u).center().drag();
EXAMPLE
// a double spiral with speed set by iChange uniform
// which is controlled by the shader rate parameter/property
F.color = purple;
const fragment = `
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
// https://www.shadertoy.com/view/cl3BWr
vec2 uv = 0.5-fragCoord/iResolution.xy;
uv.y*=iResolution.y/iResolution.x;
float angle=atan(uv.y, uv.x);
float stage=sin(-iChange + 10.*(length(uv)*10.+.2*angle));
fragColor = vec4(mix(.1,.9,smoothstep(-1.,1.,stage/fwidth(stage))));
}
`;
const shader = new Shader(W, H, fragment).center();
// shader.animate({ // would animate the rate
// props:{rate:5},
// time:5,
// rewind:true,
// loop:true
// })
const slider = new Slider({
min:0,
max:1,
value:.5,
barLength:100
}).pos(50,50,RIGHT,BOTTOM).change(()=>{
shader.rate = Math.exp(slider.value*3)-1;
});
shader.rate = Math.exp(slider.value*3)-1;
EXAMPLE
// Make a chessboard with a Fragment Shader - from https://medium.com/@banksysan_10088/webgl-checkerboard-42e15490603c
// Change the col and row counts with a Stepper using Uniforms
const fragment = `
uniform vec2 counts; // cols and rows
uniform vec4 color1; // rgba
uniform vec4 color2;
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
vec2 boardCoordinates = floor(fragCoord.xy * counts.xy / iResolution.xy);
float xMod = mod(boardCoordinates.x, 2.0);
float yMod = mod(boardCoordinates.y, 2.0);
float state = mod(xMod + yMod, 2.0);
fragColor = mix(color1, color2, state);
}
`;
const start = 8;
const uniforms = new Uniforms({
counts:[start, start],
color1:[0,0,0,1],
color2:[1,1,1,1]
});
const board = new Shader(500, 500, fragment, uniforms, null, false).center(); // false for not dynamic
const stepper = new Stepper({min:1, max:20, value:start}).sca(.8).pos(0,30,CENTER,BOTTOM).change(()=>{
uniforms.counts_A = stepper.value;
uniforms.counts_B = stepper.value;
board.update(); // update needed as dynamic is set to false
S.update();
});
EXAMPLE
// make a chessboard from a little bw image - from https://medium.com/@banksysan_10088/webgl-checkerboard-42e15490603c
// not sure if this is the easiest or only way to do this...
new Frame(FIT, 1024, 768, light, dark, ready, "board.jpg");
function ready() {
const vertex = `
in vec3 vertexPosition;
out vec3 vPosition; // will get passed to fragment shader
void main() {
vPosition = vertexPosition;
gl_Position = vec4(vertexPosition, 1.0);
}
`;
const fragment = `
uniform sampler2D TEXTURE; // texture captured here
in vec3 vPosition;
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
// texture comes in flipped and on different coordinates
vec2 normalizedCoordinates = (vPosition.xy * vec2(0.5, -0.5)) + vec2(0.5, 0.5);
fragColor = texture(TEXTURE, normalizedCoordinates); // note this is texture2D() in OpenGL 1
}
`;
const before = function(program, gl, canvas) {
const textureImageElement = new Pic("board.jpg").image;
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // nearest as linear will blend
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImageElement);
}
const board = new Shader(500, 500, fragment, null, vertex, false, before).center();
}
EXAMPLE
// make a chessboard with the Vertex Shader - from https://medium.com/@banksysan_10088/webgl-checkerboard-42e15490603c
// adding only certain squares - add a Fragment Shader with a color to change the default black
const after = function(program, gl, canvas, vertexData) {
const counts = [8,8];
const size = {width:2/counts[0], height:2/counts[1]};
let rowAlternate = true;
for (let i=-1; i<1; i+=size.width) {
let cellAlternate = rowAlternate;
for (let j=-1; j<1; j+=size.height) {
cellAlternate = !cellAlternate;
if (cellAlternate) continue; // do not add anything
const v1 = [i, j];
const v2 = [i, j + size.height];
const v3 = [i + size.width, j + size.height];
const v4 = [i + size.width, j];
vertexData.push(...v1);
vertexData.push(...v3);
vertexData.push(...v2);
vertexData.push(...v3);
vertexData.push(...v1);
vertexData.push(...v4);
}
rowAlternate = !rowAlternate;
}
}
new Rectangle(500,500,white).center();
const board = new Shader({
width:500,
height:500,
dynamic:false,
postCall:after,
strip:false // use TRIANGLES not TRIANGEL_STRIP (might not show on iOS)
}).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 500) the width of the Shader
this can be retrieved in the Shader code as iResolution.x
height - (default 500) the height of the Shader
this can be retrieved in the Shader code as iResolution.y
fragment - provide the code as a string for the Fragment Shader which affects the pixels
This can be passed in as a variable with `` for multiline or preloaded as an asset and read using asset("filename.glsl")
ShaderToy uses "void mainImage(out vec4 fragColor, in vec2 fragCoord) {}"
But basic GLSL uses main(), fragColor for OUT, and gl_FragCoord as IN
ZIM converts the ShaderToy so that you can use either.
To see the final Fragment Shader in the console set the Shader() log parameter to true
Here is the default Fragment Shader for OpenGL 3 (verion 1 is slightly different):
// START AUTO - do not include below
#version 300 es
precision mediump float;
// plus all the default Uniforms mentioned above
// END AUTO - do not include above
void main() {
vec2 fragCoord = gl_FragCoord.xy; // a 2D variable of IN coordinates
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); // OUT variable
}
uniforms - (default null) a ZIM Uniform object or an object literal {} with uniform names and values (use arrays for vectors)
if a {} is passed in, a Uniform object will be made and in either case available as the uniform property of the Shader
the uniform properties match the {} properties except any array is made into individual properties to make animation easier
For instance, passing in:
{
alpha:.5,
position:[100,200]
}
would result in three properties on the uniform object:
shader.uniform.alpha // .5
shader.position_A // 100
shader.position_B // 200
These could be animated or wiggled like:
shader.uniform.animate({position_A:300}, 2); // animate position.x inside the shader
shader.wiggle("alpha", .5, .1, .4, 1, 2); // wiggle alpha inside the shader - probably on the "z" or "a" component of a color vec4
vertex - provide the code as a string for the Vertex Shader which affects the points
this will be used less with 2D outputs - see the Fragment Shader parameter for similar details
To see the final Fragment Shader in the console set the Shader() log parameter to true
Here is the default Vertex Shader for OpenGL 3 (verion 1 is slightly different):
// START AUTO - do not include below
precision mediump float;
// plus all the default Uniforms mentioned above
vec2 fragCoord = gl_FragCoord.xy; // a 2D variable of IN coordinates
// END AUTO - do not include above
void main() {
gl_Position = vec4(vertexPosition, 0.0, 1.0); // OUT variable
}
dynamic - (default true) set to false to not update the uniforms of the shaders constanty
preCall - (default null) a function to run just before before gl.useProgram(program); and after createProgram(gl, vertex, fragment)
the function will receive (program, gl, canvas) arguments to its parameters
postCall - (default null) a function to run after createProgram(gl, vertex, fragment) and gl.useProgram(program);
the function will receive (program, gl, canvas, vertexData) arguments to its parameters
Note: the vertexData is a [] and can be filled in this function
if it is not filled then it defaults to two triangles making a rectangle of width and height
Also see the strip parameter below
rate - |ZIM VEE| (default 1) set the rate of the iChange uniform.
many shaders use iTime to animate the effect. Instead, you can use an iChange uniform
and setting a rate of 2 will animate it twice as fast, .5 half as fast, etc.
this can be set with a ZIM VEE value and can also be adjusted with the rate property of the shader
(this could also be done with the iFrameRate uniform but then the Ticker.setFPS() would have to be changed)
version - (default "#version 300 es") string version to add to top of shader code - would suggest leaving this as default
use "" for lower versions. Higher versions probably will work using the #
canvas - (default a canvas tag) a canvas tag will be created for the Shader or pass in an existing canvas tag
this will be available as the canvas property
vertexPosition - (default "vertexPosition") the variable name for the vertexPosition
strip - (default true) use gl.TRIANGLE_STRIP - set to false to use gl.TRIANGLES for vertex data
Note: could not get gl.TRIANGLES working on iOS (iPad2)
strip:true will use vertexData = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0]; // two triangles strips
strip:false will use: vertexData = [-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0]; // two triangles
in either case, if vertexData is set in the postCall then this overrides the default vertexData above.
log - (default false) - set to true to log the vertex and fragment shaders in the console - in that order
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
update() - update the shader - not needed if dynamic is true (default)
clone() - makes a copy of the Shader
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Bitmap (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(), etc.
PROPERTIES
type - holds the class name as a String
dynamic - get or set whether the shader is dynamic
rate - |ZIM VEE| get or set the rate of the iChange uniform - can use for animating the shader - see also the rate parameter
canvas - the canvas for the shader
gl - the WebGL context for the canvas for the shader
uniforms - the uniforms object stored on the shader - use uniforms.obj for the original object literal
uniforms holds all the properties as individual properties
vectors (arrays) are accessed as vector_A, vector_B, vector_C, vector_D
see ZIM Uniforms for more info
fragment - the fragment shader - also see the log parameter to view final shaders in console
vertex - the vertex shader
program - the WebGL program with the shaders
ticker - the ZIM Ticker that runs the updates
ALSO
see ZIM Bitmap for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Bitmap properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseEnabled, parent, etc.
EVENTS
See the CreateJS Easel Docs for Bitmap events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
ShaderOverlay
zim class - extends a zim.Tag
DESCRIPTION
ShaderOverlay is a ZIM Tag() that holds a canvas with a shader from provided shader code.
This is the same as ZIM Shader() so see the Docs for Shader above.
The only difference is that the shader canvas is placed in a Tag() so overlayed on ZIM.
This can also be underlayed by setting the z-index of the tag.
The advantage of a tag is that the canvas is used directly with its WebGL context
rather than passed into a Bitmap() to be displayed on the Canvas2D context.
The disadvantage is that the tag can only be overlayed or underlayed
and not be in the normal ZIM canvas container levels.
Also, if manually adjusting, a shaderOverlay.update() might need to be called.
But for the most part, the Tag() should take care of it - for instance, resizing the window.
See ZIM Tag() for more tips regarding update().
EXAMPLE
new Frame(FILL, 1024, 768, clear, clear, ready);
function ready() {
const fragment = `
void main() {
vec2 uv = gl_FragCoord.xy / iResolution.xy;
vec3 color = 0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0,2,4));
gl_FragColor = vec4(vec3(color), 1.0);
}
`;
const shader = new zim.ShaderOverlay(W, H, fragment).center();
shader.tag.style.zIndex = -50; // put shader beneath stage
const list = new List({
backdropColor:faint,
bgColor:white.toAlpha(.5),
rollBgColor:dark.toAlpha(.5),
selectedBgColor:dark.toAlpha(.8),
}).sca(1.5).center();
F.on("resize", ()=>{list.center();});
} // end ready
Uniforms
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes an object to hold uniforms for a ZIM Shader() or ShaderOverlay().
(This is not to be used as a display object despite extending a Container)
Uniforms are variables to pass in to the shader code.
They are often arrays to make vectors and array values are hard to animate.
ZIM Uniforms stores each array element as an individual property.
Uniforms extends a Container giving it animate() and wiggle() methods.
This means we can animate or wiggle any of the Uniforms properties
and ZIM will update the shader if the shader's dynamic parameter or property is true.
HOW IT WORKS
An object literal {} is passed into the Uniforms(obj).
This will have all the uniform names and values.
If the value is an array that is used to set vector uniforms, then ZIM splits this up
so that each array value has a property called the name_A, name_B, name_C, name_D as needed.
There are only ever 2, 3, or 4 component vectors.
If the value is a single value, then it is stored as the name alone.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const uniforms = new Uniforms({
age:20,
color:[.5, .2, .8, 1]
});
// the the Uniforms object will have:
zog(uniforms.age); // 20
zog(uniforms.color_A); // .5
zog(uniforms.color_B); // .2
zog(uniforms.color_C); // .8
zog(uniforms.color_D); // 1
uniforms.wiggle("color_A", .5, .2, .4, 1, 2); // would wiggle the red
// inside the shader they must be declared if they are to be used
// uniform float age;
// uniform vec4 color;
const fragment = `
uniform vec4 color; // declare our uniform - only using color, age will be ignored
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
fragColor = color; // gl_FragColor or fragColor is the default output
}
`;
new Shader(500, 500, fragment, uniforms).center().drag(); // draggable animated color box
PARAMETERS
obj - the object literal {} with uniform properties and values
METHODS
update() - update the uniforms as long as dynamic is true or the update() method of the shader is called
this is handled automatically by the shader update() so may as well call update() on shader
PROPERTIES
type - holds the class name as a String
obj - the original object literal - its properties get updated as the uniforms properties are updated
***
Each property in the object literal
with arrays being split into a property for each element in the format
name_A, name_B, name_C, name_D as dicted by the number of elements in the value for the property
{year:2024, dimensions:[200,500]}
would get:
uniforms.year = 2024
uniforms.dimensions_A = 200
uniforms.dimensions_B = 500
CLOSE ▲PAGE ▤CODE ▤
--------------ZIM SHAPES
EXPAND ▼ CustomShape(x, y, w, h)
CustomShape
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Used internally to make ZIM Shapes - Circle, Rectangle, Triangle, etc.
Holds the following properties in common:
color, colorRange, borderColor, borderWidth, thickness, dashed, dashedOffset, corner
Holds the following functions in common: (most methods applied through ZIM 4TH methods)
setColorRange, cloneAll(), linearGradient (depreciated), radialGradient (depreciated)
NOTE
this is NOT a generic Shape - see the zim.Shape() class for that.
EXAMPLE
// would recommend just extending a Container() for custom shapes / objects
// unless properties listed above are needed over multiple projects
// but it could be done with matching various private properties, etc.
// also note that a Blob can make just about any shape...
const Smile = function(color) {
this.super_constructor(-100,-20,200,70);
this._color = color;
this.shape = new Shape().addTo(this);
// this is an example of how ZIM changes shape color
// will need to go through and do similar things for borderColor, etc.
this.colorCommand = this.shape.f(this._color).command;
this.shape.mt(-100,-20).bt(0,70,0,70,100,-20);
}
extend(Smile, CustomShape);
const s = new Smile(red).center();
timeout(1, function () {
s.color = blue;
S.update();
});
Circle
zim class - extends a zim.CustomShape which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a circle shape inside a container.
The registration and origin will be the center.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Circle(50, red).center();
// or with 10 pixel grey stroke
const circle = new Circle(50, red, grey, 10).center();
// change the color of the circle to a radial gradient fill
circle.color = new RadialColor([yellow,green], [0, .7], 0, 0, 20, 0, 0, 50);
// make a half circle - or any percent of a circle
new Circle({radius:200, color:pink, percent:50}).center();
EXAMPLE
const circle = new Circle({min:10, max:50}, [red, green, blue]).center();
interval(1, ()=>{
// apply a different values picked from original ZIM VEE values
zog(circle.veeObj)
circle.radius = Pick.choose(circle.veeObj.radius); // or zik(circle.veeObj.radius)
circle.color = Pick.choose(circle.veeObj.color);
S.update();
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
radius - |ZIM VEE| (default 50) the radius (from the center to the edge or half the diameter) ;-)
color - |ZIM VEE| (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - |ZIM VEE| (default null) the stroke color
borderWidth - |ZIM VEE| (default 1 if stroke is set) the size of the stroke in pixels
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
percent - (default 100) set to a percentage of a circle (arc) - registration stays at radius center, bounds shrink to arc
percentClose - (default true) set to false to not close the border of a circle with percent set
percentArc - (default false) set to a percent to make moon shapes - must have percent turned on
the value is the distance the arc-making circle is placed from the original circle's edge
this distance is given as a percentage of the original circle's radius
so if percentArc is set to 0 then the arc-making circle is at the radius (the edge) of the original circle
if the percentArc is set to 50 then the arc-making circle is half the radius outside the original radius and the arc is less
if the percentArc is set to -50 then the arc-making circle is half the radius inside the original radius and the arc is more
Note, due to canvas winding, the arc will not do very thin cresents as expected
instead once the inner arc is as wide as the outer arc, it makes a straight line
for thin crecents, overlap the circle with a circle that matches the background color
or if the background is an image, etc. then mask a clone of the background with the arc circle
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
// note, not all applicable to a Circle - perhaps just ignoreScale...
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
Warning: clone does not clone any content added to a shape - use a Container for that - see cloneAll()
cloneAll(exact, style, group, inherit) - copies shape and any custom content in shape - experimental
exact (default false) in theory will copy ZIM VEE values as they are in the original
see main class for style, group, inherit parameters
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - gives access to the circle shape
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
depreciated - see ZIM GradientColor, RadialColor and BitmapColor
borderColor - get and set the stroke color
borderColorCommand - access to the CreateJS stroke command for bitmap, linearGradient and radialGradient strokes
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Stroke.html
borderWidth - get and set the stroke size in pixels
borderWidthCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
radius - gets or sets the radius.
The radius is independent of scaling and can be different than the width/2
Setting the radius redraws the circle but any current scaling is kept
percentage - get or set the percent of the circle (see percent parameter)
NOTE not percent property which interferes with animate percent
percentClose - get or set the percent close of the circle (see percentClose parameter)
percentArc - get or set the percent arc (see percentArc parameter)
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
Rectangle
zim class - extends a zim.CustomShape which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a rectangle shape inside a container.
The registration and origin will be top left corner.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Rectangle(200, 100, blue).center();
// or with rounded corners
new Rectangle({width:200, height:100, color:blue, corner:20}).center();
// or with individual corners
new Rectangle({width:100, height:100, corner:[50,0,50,0]}).center();
// or with skewed corners
// this will have a radius of 50 in the horizontal but 20 in the vertical
new Rectangle({width:100, height:100, corner:[50,20]}).center();
// or a combination of corner values and skewed values
new Rectangle({width:100, height:100, corner:[0, 50, [10,50], [40, 20]}).center();
// or with 2 pixel white stroke
new Rectangle(200, 100, blue, white, 2).center();
// fill the rectangle with a Bitmap fill assuming icon has been loaded - not the image property
new Rectangle(200, 300, new BitmapColor(new Pic("icon.png"))).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - |ZIM VEE| (default the height if provided else 100) the width
height - |ZIM VEE| (default the width if provided else 100) the height
color - |ZIM VEE| (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - |ZIM VEE| (default null) the stroke color
borderWidth - |ZIM VEE| (default 1 if stroke is set) the size of the stroke in pixels
corner - (default 0) the round of corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
can also be an array of [horizontal, vertical] which skews each corner
can also be a combination array of values and skew arrays
[topLeft, [horizontal, vertical], bottomRight, [horizontal, vertical]]
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
scaleDimensions - (default true) set to false to redraw the shape rather than scale the shape
when using width, height widthOnly, and heightOnly
a false setting will keep the corner and the borderWidth the same size
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
Warning: clone does not clone any content added to a shape - use a Container for that - see cloneAll()
cloneAll(exact style, group, inherit) - copies shape and any custom content in shape - experimental
exact (default false) in theory will copy ZIM VEE values as they are in the original
see main class for style, group, inherit parameters
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - gives access to the rectangle shape
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
depreciated - see ZIM GradientColor, RadialColor and BitmapColor
borderColor - get and set the stroke color
borderColorCommand - access to the CreateJS stroke command for bitmap, linearGradient and radialGradient strokes
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Stroke.html
borderWidth - get and set the stroke size in pixels
borderWidthCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
corner - get or set the corner or array of corners (see corner parameter)
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
scaleDimensions - get or set whether the shape scales when width, height, widthOnly or heightOnly are used
also see the scaleDimensions paramater
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
Triangle
zim class - extends a zim.CustomShape which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a triangle shape inside a container using three line lengths.
Passing one length parameter makes an equilateral triangle.
Passing two length parameters makes an isosceles triangle.
Passing -1 as the middle or last length parameter makes a 90 degree triangle.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Triangle(200, null, null, "green").center();
// all three sides specified - tall pointy triangle with yellow stroke of 10 pixels
new Triangle(100, 200, 200, "green", "yellow", 10).center();
// here we adjust so rotation looks better
const tri = new Triangle({a:200, color:"green", adjust:30})
.center()
.animate({obj:{rotation:360}, time:3, ease:"linear", loop:true});
// here we fill the triangle with a linear gradient color
tri.color = new GradientColor([green, blue ,green], [.2, .5, .8], 0, 0, tri.width, 0);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
a, b and c - |ZIM VEE| (default 100) the lengths of the sides
a will run horizontally along the bottom
b is upwards and c is back to the origin
if b or c is set to -1 will assume a 90 angle
color - |ZIM VEE| (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - |ZIM VEE| (default null) the stroke color
borderWidth - |ZIM VEE| (default 1 if stroke is set) the size of the stroke in pixels
corner - (default 0) the round of corner
can also be an array of [bottomLeft, bottomRight, top]
center - (default true) puts the registration point to the center
adjust - (default 0) pixels to bring center towards vertical base
the actual center is not really the weighted center
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
Warning: clone does not clone any content added to a shape - use a Container for that - see cloneAll()
cloneAll(exact style, group, inherit) - copies shape and any custom content in shape - experimental
exact (default false) in theory will copy ZIM VEE values as they are in the original
see main class for style, group, inherit parameters
exact (default false) in theory will copy ZIM VEE values as they are in the original
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - gives access to the triangle shape
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
depreciated - see ZIM GradientColor, RadialColor and BitmapColor
borderColor - get and set the stroke color
borderColorCommand - access to the CreateJS stroke command for bitmap, linearGradient and radialGradient strokes
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Stroke.html
borderWidth - get and set the stroke size in pixels
borderWidthCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
corner - get or set the corner or array of corners (see corner parameter)
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
one, two, three - read only - points with x, y properties for bottom left, bottom right, top right
angles - read only - Array of angles [bottom left, bottom right, top right]
adjusted - read only - the value of the adjust parameter or 0 if no adjust was supplied
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊BITS VIDS
Poly
zim class - extends a zim.CustomShape which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a regular polygon with radius like a Circle.
The number of sides can be set as well as a pointSize that will make star-like shapes
The registration and origin will be the center.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Poly(200, 5, 0, pink).center(); // pentagon
new Poly(200, 5, .6, pink).center(); // five point star
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
radius - |ZIM VEE| (default 50) the radius (from the center to the edge or half the diameter) ;-)
sides - |ZIM VEE| (default 5) the number of sides
pointSize - |ZIM VEE| (default 0) a factor that will indent or outdent the sides to form stars
0 is no indent - 1 is a complete indent - which will have no fill and if there is a border will look like a stick figure
beyond 1 is cool - it overlaps on itself and makes multiple patterns
color - |ZIM VEE| (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - |ZIM VEE| (default null) the stroke color
borderWidth - |ZIM VEE| (default 1 if stroke is set) the size of the stroke in pixels
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
flat - (default false) by default all Poly star shapes point up - set flat to true to keep a flat side down
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
cloneAll(exact style, group, inherit) - copies shape and any custom content in shape - experimental - usually shapes do not have content (use a Container)
exact (default false) in theory will copy ZIM VEE values as they are in the original
see main class for style, group, inherit parameters
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
radius - gets or sets the radius.
The radius is independent of scaling and can be different than the width/2
Setting the radius redraws the circle but any current scaling is kept
sides - get or set the sides of the shape
pointSize - get or set the point size of the shape (can be animated too)
shape - gives access to the poly shape
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
depreciated - see ZIM GradientColor, RadialColor and BitmapColor
borderColor - get and set the stroke color
borderColorCommand - access to the CreateJS stroke command for bitmap, linearGradient and radialGradient strokes
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Stroke.html
borderWidth - get and set the stroke size in pixels
borderWidthCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Line
zim class - extends a zim.CustomShape which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a straight line with a length and thickness.
See also ZIM Squiggle() with points:[[0,0], [100,0], etc. with Bezier handles
See also ZIM Shape() for custom lines, curves, etc.
The registration and origin will be at the start point at the left.
Start point and end point can be adjusted in various ways to accommodate animation, etc.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Line(500).center(); // centered line
EXAMPLE
new Line({points:[[0,0],[100,0],[100,100],[200,100]]}).center(); // over, up, over, etc.
// or with quadratic curves:
// 100,0 is control point to x,y of 100,50
new Line({points:[[0,0],[100,0,100,50],[100,100,200,100]]}).center(); // over, up, over
// or with bezier curves:
// 100,0 is first control point, 100,0 is second control point and 100,50 is final point
new Line({points:[[0,0],[100,0,100,0,100,50],[100,100,100,100,200,100]]}).center(); // over, up, over
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
length - |ZIM VEE| (default 100) the length of the line - see also length property and start and end point properties
thickness - |ZIM VEE| (default 3) the size of the stroke in pixels
color - |ZIM VEE| (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
startHead - |ZIM VEE| (default "none") the start head of the line - set to "arrow" (or "triangle") or "circle" or a custom DisplayObject - probably centerReg this
endHead - |ZIM VEE| (default "none") the end head of the line - set to "arrow" (or "triangle") or "circle" or a custom DisplayObject - probably centerReg this
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
lineType - (default "straight") - by default the line is a straight line between points
set to "corner" to draw only horizontal and vertical lines at 90 degree angles between lines (see lineOrientation)
set to "curve" to draw horizontal and vertical lines with curves between lines (see lineOrientation)
lineOrientation - (default AUTO) - for lineType other than straight automatically decide between horizontal or vertical
set to HORIZONTAL to draw two horizontal lines and one vertical line between points
set to VERTICAL to draw two vertical lines and one horizontal line between points
curveH - (default 100) - for "curve" lineType this is the horizontal distance of the curve
curveV - (default 100) - for "curve" lineType this is the vertical distance of the curve
points - (default null) an Array of points for the line which will ignore length and lineType parameters
points in the array can have the following formats (a mix is okay too):
[x,y] points for straight lines. This format should also be used for first point
[cpX, cpY, x, y] for quadratic curve to with a single control point followed by the destination point
[cp1X, cp1Y, cp2X, cp2Y, x, y] for Bezier curve to with start and end control points followed by the destination point
// see the ZIM Shape docs (or https://www.createjs.com/docs/easeljs/classes/Graphics) for details on the curves
startLength - |VEE| (default null) for lineType corner or curved, the length the line will start.
should be less than half the line distance (either vertical or horizontal depending on lineOrientation) otherwise ignored
varying this will avoid overlap when used with Connectors - also see endLength
for the corner lineType both can be set but usually one would be set
for the curved lineType the endLength will be chosen over the startLength
endLength - |VEE| (default null) for lineType corner or curved, the length the line will end.
should be less than half the line distance (either vertical or horizontal depending on lineOrientation) otherwise ignored
varying this will avoid overlap when used with Connectors - also see startLength
for the corner lineType both can be set but usually one would be set
for the curved lineType the endLength will be chosen over the startLength
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setPoints(a, b, c, d) - pass in two ZIM Points or four numbers to set start points and end points or an array of points
this will not change the x and y of the shape
also see startPoint, endPoint, startX, startY, endX, endY properties
if an array is used the points are remade like when made with the points parameter
from(a, b, localToLocal) - pass in a ZIM Point or two numbers to set the start point
if a DisplayObject is passed in then it will locate the point adjusting for coordinate space (unless localToLocal is false)
to(a, b, localToLocal) - pass in a ZIM Point or two numbers to set the end point
if a DisplayObject is passed in then it will locate the point adjusting for coordinate space (unless localToLocal is false)
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
cloneAll(exact style, group, inherit) - copies shape and any custom content in shape - experimental - usually shapes do not have content (use a Container)
exact (default false) in theory will copy ZIM VEE values as they are in the original
see main class for style, group, inherit parameters
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
** below will not change the x and y of the shape
** if points is being used: length, startPoint, start and end X and Y, endPoint and angle are ignored - use the point property
length - gets or sets the length of the line - will grow from its registration point
startPoint - (ZIM Point or x,y object) get or set the start point
startX - get or set the start x point - allows for animation
startY - get or set the start y point - allows for animation
endPoint - (ZIM Point or x,y object) get or set the end point
endX - get or set the end x point - allows for animation
endY - get or set the end y point - allows for animation
startHead - get or set the start head - see startHead parameter
endHead - get or set the end head - see endHead parameter
startLength - get or set the start length of the line (see startLength parameter)
endLength - get or set the end length of the line (see endLength parameter)
angle - gets (not sets) the current angle relative to the line (does not include line rotation)
points - get and set the points array (see points parameter) - ignoring all settings above
** above will not change the x and y of the shape
shape - gives access to the line shape
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
depreciated - see ZIM GradientColor, RadialColor and BitmapColor
thickness - get and set the stroke size in pixels
thicknessCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
lineType - read only access to type of line "straight", "corner", "curve"
lineOrientation - get or set the lineOrientation to AUTO, HORIZONTAL or VERTICAL - see Line params for info
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Squiggle
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a squiggly line with a number of points.
The points have Bezier controls - little handles that change the shape of the line.
The type of control can be specified overall and individually - and can be hidden or shown
The type of control can be changed by double clicking the point - colors of the handles will change
Points can be added by clicking on the line or removed by SHIFT clicking a point.
CTRL Z will undo adding or removing a point
The shape of the line can be recorded with the recordData() method and recreated with the setData() method
The Squiggle is set by default to show and hide controls when clicked
It is also draggable by default when the controls are showing
It can be set to copy with a shift click
SEE: https://www.youtube.com/watch?v=P2hDe5JCINY for Blob and Squiggle Basics
SEE: https://zimjs.com/paths/ to make points for Blob and Squiggle
MULTIPLE SELECT
Multiple points can be selected with the CTRL key held and then dragged
or moved with the keyboard arrows (moves 10 pixels with shift key down)
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Squiggle().center(); // makes a line with default 4 points with Bezier controls
EXAMPLE
new Squiggle({points:2, controlType:"none"}).pos(100,100); // makes a diagonal straight line that is editable
// there are so many examples for Blob and Squiggle
// see https://www.youtube.com/watch?v=P2hDe5JCINY
// Add a new second smaller part to the Squiggle
// reverse points from right to left and animate along Squiggle
const s1 = new Squiggle({showControls:false}).center();
const s2 = new Squiggle()
.transformPoints("scale", .5)
.transformPoints("x", s1.width);
s.appendPoints(s2.points).reversePoints();
new Circle(10).addTo().animate({path:s1}, 5);
EXAMPLE
// split Squiggle and change color of second part
const s1 = new Squiggle().center();
const s2 = s1.splitPoints(2);
s2.color = red;
EXAMPLE
// split Blob into Squiggles
const b1 = new Blob().center();
const s1 = b1.makeSquiggle(0).loc(b1);
const s2 = s1.splitPoints(2).loc(b1);
s2.color = red;
b1.removeFrom();
// // and put back again
// s1.appendPoints(s2.points, "mirror");
// const b2 = s1.makeBlob().loc(s1);
// b2.color = blue;
// b2.borderColor = null;
// s1.removeFrom();
// s2.removeFrom();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
color - |ZIM VEE| (default green) the line color as any CSS color including "rgba()" for alpha
thickness - (default 2) the thickness of the line in pixels
points - (default 5) a number of points to start with to make the shape
OR an SVG path like: points:"M0,129.5c22,0,40-31,40-41c0-8-3.2-13-10-13" etc. (also see SVGContainer)
OR an array of points as follows - https://zimjs.com/paths has a tool to make points in this format
[[controlX, controlY, circleX, circleY, rect1X, rect1Y, rect2X, rect2Y, controlType], [etc]]
controlX and controlY - the x and y location of the control Container which holds the point circle and the two control rectangles
rect1X, rect1Y, rect2X, rect2Y - (default based on controlLength) the x and y location of the control rectangles relative to the control location
circleX and circleY - (default 0) the x and y location of the circle relative to the control location (usually 0, 0)
controlType - (default main controlType parameter or "straight" if not controlType parameter) the point's controlType "none", "mirror", "straight" or "free"
custom points will start with approximateBounds() called
but approximateBounds() must be called manually anytime afterwards when new bounds are desired.
length - (default 300) the default length of line used to create the squiggle (also specifies the squiggle's bounds(0, 0, length, thickness))
controlLength - |ZIM VEE| (default radius*numPoints/4) specify a Number to override the calculated default
controlType - (default "straight") one of four String values as follows:
none - there are no control rectangles (they are actually set at 0,0). This makes a corner at the circle point.
mirror - the control rectangles reflect one another about the point circle - lengths are kept even
straight - the control rectangles keep a straight line through the point circle but length is independent
free - the control rectangle moves independently from the other control rectangle
** The controlType can be specified for each point - see the points parameter
** The controlType can be changed by doubleClicking the point circle to cycle through the controls in the order above - unless the lockControlType is set to true
lockControlType - (default false) set to true to disable doubleClicking of point circles to change controlType
showControls - (default true) set to false to start with controls not showing - can change this after with controlsVisible property or showControls() and hideControls() methods
lockControls - (default false) set to true to lock the editing of controls - can't move the points or handles - but can see them if showControls is set to true
handleSize - (default 20 mobile 10 for non-mobile) the size of control boxes and affects the circles too proportionally
allowToggle - (default true) set false to let turn off clicks showing and hiding controls
move - (default true) set to false to disable dragging when controls are showing
can also set to "always" to allow movement when controls are not showing
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
onTop - (default true) set to false to not bring shape to top of container when dragging
circleColor - (default light) set the circle color of the controls
circleBorderColor - (default dark) set the circle border color of the controls
stickColor - (default darker) set the stick color of the controls
stickThickness - (default 1) set the stick thickness of the controls
selectColor - (default white) the color of the selected circle or rectangle of the controls if selectPoints is true
selectPoints - (default true) set to false to not allow point controls to be selected for keyboard control
editPoints - (default true) lets user add points by pressing on shape path or remove points by shift click or hold
set to "anywhere" to let users add points anywhere - will add points with controlType:"none"
set to false to not allow adding or removing points with shift click or hold
interactive - (default true) set to false to turn off controls, move, toggle, select, edit - leaving just the shape
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
approximateBounds(num, showPoints, margin) - update the bounds based on a Rectangle
that surrounds the number of points (default 80) distributed around the object path
set showPoints to true to draw little dots on points
margin increases (or if negative decreases) the bounds on all sides by the margin
use outline() after object has been added to the stage to see the bounds
Squiggles with custom points will start with approximateBounds() called
but approximateBounds() must be called manually anytime afterwards when new bounds are desired.
addPoint(percent, controlType) - add a point at a percent (100) of the total curve
this is handy to make path have the same number of points for animate() path tweens
controlType can be as specified in main points parameter
returns index of new point
addPoints(num, controlType, startPoint, spread, dataOnly, points, even) - add num points between existing points
controlType can be as specified in main points parameter
specify a startPoint to add points between the startPoint and the next point (one segment of points)
spread (default false) set to true to spread points evenly around path rather than evenly between segments
dataOnly and points are used internally
returns object for chaining
removePoint(index) - remove a point at the specified index
interpolate(num, startPoint, spread, points, even) - get point data {x,y} for existing points and num (default 1) points inbetween
used with hitTestPath() and animate() drag on path - also add points (note add points does not use even:true)
specify a startPoint to get points between the startPoint and the next point (one segment of points)
spread (default false) set to true to spread number of points around path rather equal number between segments
points (default all points) the points to work with in the same format as the points property
even (default false) set to true to use zim.Bezier() with even turned on for even percentage distribution
returns an array of point objects with x, y properties and an r property for ratio of distance along path
recordData(toJSON) - returns an object with x, y, points, color, borderColor, borderWidth, move, toggle, controls PROPERTIES to be used with setData() method
if toJSON (default false) is set to true, the return value is a JSON string
the points data comes from the points property
setData(data, fromJSON) - sets the properties to match the data object passed in - this should come from recordData()
if fromJSON (default false) is set to true, it will assume a JSON string is passed in as data
the points data is parsed with the set setPoints() so the number of points should be the same
returns object for chaining
getPoints(popup) - returns an array with the same format as the points parameter - or can just use points property - also recordPoints() for backwards compatibility
popup - (default false) set to true to open a zim Pane (squiggle.pane) with the points in a zim TextArea (squiggle.textArea) (click off to close)
NOTE: the TextArea output uses JSON.stringify() - to add the points to the points parameter of the Squiggle use JSON.parse(output);
NOTE: using zog(JSON.stringify(squiggle.recordData()))... the console will remove the quotes from the controlTypes so those would have to be manually put back in before parse() will work
also see points property
setPoints(data) - sets the Squiggle points to the data from getPoints
this does not remake the Squiggle but rather shifts the controls so the number of points should be the same
also see points property
changeControl(index, type, rect1X, rect1Y, rect2X, rect2Y, circleX, circleY, update) - change a control type and properties at an index
accepts ZIM DUO normal parameters or configuration object literal with parameter names as propterties
passing in null as the index will change all points to the specified properties
the update parameter defaults to false so set to true to show update or call update() below
this is so multiple changes can be batched before calling update - for instance when animating blobs.
transformPoints(transformType, amount, x, y, approximateBounds) - scale, rotate, move points without affecting controls or borderWidth - returns object for chaining
transformType - String any of: "scale", "scaleX", "scaleY", "rotation", "x", "y"
amount - the amount to transform
x, y - (default 0, 0) the x and y position to transform about
approximateBounds defaults to true - set to false to not call approximateBounds after transforming points
reversePoints() - reverse the order of the points
this also swaps each rectangle in the Bezier controls
also see the Code module for reversePoint(points) function to operate on data points in Squiggle format
appendPoints(points, controlType) - add points at end of points - updates Squiggle
it is assumed that the first point of the new points is in the same place as the last point of the Squiggle
by default these will transfer control types but can override with controlType
this will not have immediate effect but will be triggered when the joining point handle is moved
prependPoints(points, controlType) - add points at start of points - updates Squiggle
it is assumed that the last point of the new points is in the same place as the first point of the Squiggle
by default these will transfer control types but can override with controlType
this will not have immediate effect but will be triggered when the joining point handle is moved
splitPoints(index) - breaks the Squiggle into two Squiggles at the index (length / 2)
the original Squiggle is the first Squiggle
returns a reference to the second Squiggle
makeBlob(controlType, mergeDist) - makes a new Blob from the Squiggle
returns the new Blob - the Squiggle remains unchanged so may need to remove it
controlType (default "free" if not merged and "mirror" if merged)
controlType for the joined end points - also see mergeDist below
this will not change the control sticks until their handles are dragged
mergeDist (default 5) merges overlapping end points (within this pixel distance)
update(normalize) - update the Squiggle if animating control points, etc. would do this in a Ticker
set normalize (default false) to true to use pointsAdjusted for rotated and scaled points
and if animating along the path after setting rotation or scale on point
just leave out if only animating points
showControls() - shows the controls (and returns squiggle) also see controlsVisible property
hideControls() - hides the controls (and returns squiggle) also see controlsVisible property
toggle(state - default null) - shows controls if hidden and hides controls if showing (returns the object for chaining)
or pass in true to show controls or false to hide controls
traverse(obj, start, end, time) - animates obj from start point to end point along path - thanks KV for the thought!
set start point greater than end point to traverse backwards
will dispatch a "traversed" event when done
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
getPointAngle(index) - gets the angle made by the tangent at the index provided
getSegmentPoint(point1, point2) - returns an array of [point1, controlPoint1, controlPoint2, point2]
used internally for animating to path and adding removing Bezier points
getAdjacentSegmentData(index) - returns an array of two arrays:
The first is an array of cubic Bezier points for segments adjacent and including the provided point index
each element is in the form of [point1, controlPoint1, controlPoint2, point2]
The second is an array of starting point indexes for the segments that were tested
used internally to drag an animation along the path
getCurvePoint(ratio, segmentRatios, segmentPoints, getAngle) gets a point along whole curve at the ratio (0-1) provided
along with x and y values, the point has a z value that is the index of the squiggle point before the calculated point
if the getAngle parameter is true (default false) the point also has an angle property which is the angle of the tangent at the point
ratio is 0-1 with 0 being at the first point and 1 being at the end of the last segment
segmentRatios and segmentPoints will be calculated if not provided
used internally for animating along the path - if lockControls is true, only animate will precalculate these values
linearGradient([colors],[ratios], x0,y0, x1,y1) - shortcut to thicknessCommand linearGradient method (see properties below)
radialGradient([colors],[ratios], x0,y0,radius0, x1,y1,radius1) - shortcut to thicknessCommand radialGradient method (see properties below)
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact, commands) - makes a copy of the object
exact (default false)
ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
commands (default false) makes clones with current color and borderColor commands of object
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - gives access to the shape of the squiggle
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
circleColor - get or set the circle color of the controls - requires an update() to see changes
circleBorderColor - get or set the circle borderColor of the controls - requires an update() to see changes
stickColor - get or set the stickColor - requires an update() to see changes
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
eg. shape.colorCommand.linearGradient([green, blue ,green], [.2, .5, .8], 0, 0, shape.width, 0)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Fill.html
thickness - get and set the stroke size in pixels
thicknessCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
dashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
num - get the number of points - to set, use the points property
points - get or set the points array of the Squiggle in the same format as the points parameter:
[[controlX, controlY, circleX, circleY, rect1X, rect1Y, rect2X, rect2Y, controlType], [etc]]
also see getPoints(popup) and setPoints() methods
pointsAdjusted - get points with any point rotation converted to 0 - see update(true)
pointControls - get an array of controls (a container) - use this to animate controls
pointCircles - get an array of control circles - use this to place some other object at the point
pointObjects - get an array of point objects for each point in the following format:
[[control, circle, rect1, rect2, controlType], [etc.]]
control - the container for the control that holds the circle and rectangles (also see pointControls)
circle - the control point circle (also see pointCircles)
rect1 - the first control point rectangle
rect2 - the second control point rectangle
controlType - the control type: default is "straight" (or null) and there is also "mirror", "free" and "none"
NOTE: control, circle, rect1, rect2 can be positioned or animated and controlType can be changed
NOTE: the update() method must be called if manually changing the control positions or type
NOTE: if constantly animating the controls then use a Ticker.add(function(){squiggle.update();})
NOTE: also see recordData(), setData(), getPoints(), setPoints() methods for further options
addPointFactor - (default 20) used when placing new points along edge (editPoints is true)
divides the distance between points by this amount - the smaller the more accurate but also slower
addMinDistance - (default 15) edge press needs to be within this distance to add a point to the edge
segmentPoints - a read-only array of cubic Bezier points for each segment
each element is in the form of [point1, controlPoint1, controlPoint2, point2]
used internally to animate to the path and add and remove Bezier points
segmentRatios - a read-only array of cumulative ratio lengths of segments
for instance the default five points (four segments) is [.25, .5, .75, 1]
used internally to animate to the path and attribute proportional time to each segment
controls - access to the container that holds the sets of controls
each control is given a read-only num property
sticks - access to the Shape that has the control sticks
lastSelected - access to the last selected (or created) control container
lastindex - the index number of the last selected controls
controlsVisible - get or set the visibility of the controls - or use showControls() and hideControls()
toggled - read-only Boolean property as to whether picker is showing
types - get or set the general array for the types ["mirror", "straight", "free", "none"]
changing this or removing a type will adjust the order when the user double clicks the points to change their type
this is not an array of types for each point - see the points property to access the types of each point
lockControls - Boolean to lock controls from being adjusted or not
lockControlType - Boolean to lock the type of the controls in their current state or not
allowToggle - Boolean to get or set clicking to show and hide controls
move - Boolean to drag or not drag Squiggle when controls are showing
can also set to "always" to allow movement when controls are not showing
onTop - get or set the onTop
selectPoints - get or set whether points can be selected
interactive - get or set whether the shape is interactive - toggle, move, change or add controls, etc.
keyFocus - get or set the keyboard focus on the DisplayObject - see also zim.KEYFOCUS
will be set to true if this DisplayObject is the first made or DisplayObject is the last to be used with keyboard
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event for when the bezier controls are adjusted (pressup only)
if monitoring constant change is needed add a pressmove event to Squiggle.controls
the change event object has a transformType property with values of "move", "bezierPoint", "bezierHandle", "bezierSwitch"
dispatches "controlsshow" and "controlshide" events when clicked off and on and toggle is true
dispatches an "update" event if the points are changed or a point is added or removed
this removes all listeners on the old shape and controls
so any custom listeners on shape and controls will need to be re-applied - use the update event to do so
dispatches a "traversed" event when traverse() is done - the event object has an obj property for the traversing object
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
MORE
https://zimjs.com/squigglehttps://www.youtube.com/watch?v=BA1bGBU4itI&list=PLCIzupgRt1pYtMlYPtNTKCtztFBeOtyc0
Note the points property has been split into points and pointObjects (and there have been a few property changes) since the time of the video
CLOSE ▲PAGE ▤CODE ▤TOUR😊VIDS
Blob
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a blob shape inside a container using a number of points.
The points have Bezier controls - little handles that change the shape of the Blob.
The type of control can be specified overall and individually - and can be hidden or shown
The type of control can be changed by double clicking the point - colors of the handles will change
Points can be added by clicking on the shape or removed by SHIFT clicking a point.
CTRL Z will undo adding or removing a point
The shape of the Blob can be recorded with the recordData() method and recreated with the setData() method
The Blob is set by default to show and hide controls when clicked
It is also draggable by default when the controls are showing
SEE https://zimjs.com/paths for a tool to make Blob and Squiggle shapes
SEE https://www.youtube.com/watch?v=P2hDe5JCINY for Basics Video
MULTIPLE SELECT
Multiple points can be selected with the CTRL key held and then dragged
or moved with the keyboard arrows (moves 10 pixels with shift key down)
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
with the ZIM namespace zns = false, this overwrites a JS Blob - so the JS Blob is stored as document.Blob
NOTE
if using Rive and Blobs, sometimes Rive apps use embedded images that need the JavaScript Blob()
ZIM disables Blob until the Rive app is loaded. Possibly this could conflict with a ZIM Blob
being made at the same time as the Rive app. In that case, use zim.Blob() for the blob.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Blob().center(); // makes a circle with default 4 points with Bezier controls
EXAMPLE
new Blob({
points:12, // 12 points for more complex shape
}).center();
EXAMPLE
new Blob({
color:purple,
controlType:"free", // free will be default control type (rather than "straight")
points:[
// the control position x, y
// then three point positions inside the control - so relative to the control position
// 1. circle position x, y (usually the same as the control position - so 0,0)
// 2. the location of the first control rectangle x and y
// 3. the location of the second control rectangle x and y
// then an optional specific type of control that overrides the controlType parameter (or the default type of "straight")
[-100,-100,-100,100,100,-100,0,0,"mirror"], // this will be type "mirror"
[100,-100,100,0,-50,0], // this will be type "free" because controlType parameter
[100,100], // these will be type "none" because no dimensions (or dimensions 0) specified for controls
[-100,100]
]
}).centerReg();
EXAMPLE
// Transform the original points of a Blob
// If you rotate or scale, this affects the control points - the little rectangles rotate or they scale
// To avoid this, the points themselves can be transformed (scaleX, scaleY, scale, rotation, x, y)
// This makes a square and scales it bigger without affecting control size or stroke size (if there were a stroke)
// Note the default number of points is 4 but they are arranged at the top, bottom and sides - so would make a diamond with just controlType:"none"
new Blob({controlType:"none"}).transformPoints("rotation", 45).transformPoints("scale", 2).center();
EXAMPLE
// make a Blob the shape of basic ZIM shapes
// this overrides the path parameter
new Blob({points:"circle"}).pos(200,200);
new Blob({points:new Rectangle(100,200)}).center();
new Blob({points:new Triangle()}).transformPoints("rotation", 90).pos(50,50,true,true);
// Animate one Blob into another
const targetBlob = new Blob({points:"rectangle"});
const blob = new Blob({radius:50, points:"circle", interactive:false})
.pos(200,200)
.transformPoints("rotation", -45) // to better tween to rectangle
.animate({
props:{shape:targetBlob},
time:1,
rewind:true,
loop:true
});
EXAMPLE
// split Blob into Squiggles
const b1 = new Blob().center();
const s1 = b1.makeSquiggle(0).loc(b1);
const s2 = s1.splitPoints(2).loc(b1);
s2.color = red;
b1.removeFrom();
// // and put back again
// s1.appendPoints(s2.points, "mirror");
// var b2 = s1.makeBlob().loc(s1);
// b2.color = blue;
// b2.borderColor = null;
// s1.removeFrom();
// s2.removeFrom();
EXAMPLE
// Split a blob into two blobs
const blobs = new Blob().center().splitBlob(1,3);
blobs[0].color = blue;
// or with points - cuts diagonally across blob
const blobs = new Blob().center().splitBlob(new Point(0,0), new Point(W,H));
blobs[0].color = blue;
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
color - |ZIM VEE| (default green) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - |ZIM VEE| (default null) the stroke color
borderWidth - (default 1 if stroke is set) the size of the stroke in pixels
num - get the number of points - to set, use the points property
points - (default 4) a number of points to start with to make the shape
OR a shape string of "circle", "rectangle" or "triangle"
OR a ZIM Circle, Rectangle, Triangle or Flare with any dimensions that will be matched
OR an SVG path like: points:"M0,129.5c22,0,40-31,40-41c0-8-3.2-13-10-13" etc. (also see SVGContainer)
OR an array of points as follows - see https://zimjs.com/paths for a tool to make points in this format:
[[controlX, controlY, circleX, circleY, rect1X, rect1Y, rect2X, rect2Y, controlType], [etc]]
controlX and controlY - the x and y location of the control Container which holds the point circle and the two control rectangles
circleX and circleY - (default 0) the x and y location of the circle relative to the control location (usually 0, 0)
rect1X, rect1Y, rect2X, rect2Y - (default based on controlLength) the x and y location of the control rectangles relative to the control location
controlType - (default main controlType parameter or "straight" if not controlType parameter) the point's controlType "none", "mirror", "straight" or "free"
custom points will start with approximateBounds() called
but approximateBounds() must be called manually anytime afterwards when new bounds are desired.
radius - (default 100) the default radius of the circle used to create the blob (also specifies the blob's bounds(-radius, -radius, radius*2, radius*2))
controlLength - |ZIM VEE| (default radius*numPoints/4) specify a Number to override the calculated default
controlType - (default "straight") one of four String values as follows:
none - there are no control rectangles (they are actually set at 0,0). This makes a corner at the circle point.
mirror - the control rectangles reflect one another about the point circle - lengths are kept even
straight - the control rectangles keep a straight line through the point circle but length is independent
free - the control rectangle moves independently from the other control rectangle
** The controlType can be specified for each point - see the points parameter
** The controlType can be changed by doubleClicking the point circle to cycle through the controls in the order above - unless the lockControlType is set to true
lockControlType - (default false) set to true to disable doubleClicking of point circles to change controlType
showControls - (default true) set to false to start with controls not showing - can change this after with control property or showControls() method
lockControls - (default false) set to true to lock the editing of controls - can't move the points or handles - but can see them if showControls is set to true
handleSize - (default 20 mobile 10 for non-mobile) the size of control boxes and affects the circles too proportionally
If a handleSize of 0 is chosen, then the sticks will disappear too
allowToggle - (default true) set false to let turn off clicks showing and hiding controls
move - (default true) set to false to disable dragging when controls are showing
can also set to "always" to allow movement when controls are not showing
dashed - (default false) set to true for dashed border (if borderWidth or borderColor set)
or set to an array of line size then space size, etc.
eg. [20, 10] is 20 line and 10 space repeated and [20,100,50,10] is 20 line, 100 space, 50 line, 10 space, etc.
onTop - (default true) set to false to not bring shape to top of container when dragging
circleColor - (default light) set the circle color of the controls
circleBorderColor - (default dark) set the circle border color of the controls
stickColor - (default darker) set the stick color of the controls
stickThickness - (default 1) set the stick thickness of the controls
selectColor - (default white) the color of the selected circle or rectangle of the controls if selectPoints is true
selectPoints - (default true) set to false to not allow point controls to be selected for keyboard control
editPoints - (default true) lets user add points by pressing on shape path.
set to "anywhere" to let users add points anywhere - will add points with controlType:"none"
set to false to not allow adding or removing points with click or shift click
interactive - (default true) set to false to turn off controls, move, toggle, select, edit - leaving just the shape
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:10, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
approximateBounds(num, showPoints) - update the bounds based on a Rectangle
that surrounds the number of points (default 80) distributed around the object path
set showPoints to true to draw little dots on points
use outline() after object has been added to the stage to see the bounds
Blobs with custom points will start with approximateBounds() called
but approximateBounds() must be called manually anytime afterwards when new bounds are desired.
addPoint(percent, controlType) - add a point at a percent (100) of the total curve
this is handy to make path have the same number of points for animate() path tweens
controlType can be as specified in main points parameter
returns index of new point
addPoints(num, controlType, startPoint, spread, dataOnly, points, even) - add num points between existing points
controlType can be as specified in main points parameter
specify a startPoint to add points between the startPoint and the next point (one segment of points)
spread (default false) set to true to spread points evenly around path rather than evenly between segments
dataOnly and points are used internally
returns object for chaining
removePoint(index) - remove the point at the specified index
interpolate(num, startPoint, spread, points, even) - get point data {x,y} for existing points and num (default 1) points inbetween
used with hitTestPath() and animate() drag on path - also add points (note add points does not use even:true)
specify a startPoint to get points between the startPoint and the next point (one segment of points)
spread (default false) set to true to spread number of points around path rather equal number between segments
points (default all points) the points to work with in the same format as the points property
even (default false) set to true to use zim.Bezier() with even turned on for even percentage distribution
returns an array of point objects with x, y properties and an r property for ratio of distance along path
recordData(toJSON) - returns an object with x, y, points, color, borderColor, borderWidth, move, toggle, controls PROPERTIES to be used with setData() method
if toJSON (default false) is set to true, the return value is a JSON string
the points data comes from the points property
setData(data, fromJSON) - sets the properties to match the data object passed in - this should come from recordData()
if fromJSON (default false) is set to true, it will assume a JSON string is passed in as data
the points data is parsed with the set setPoints() so the number of points should be the same
returns object for chaining
getPoints(popup) - returns an array with the same format as the points parameter - or can just use points property - also recordPoints() for backwards compatibility
popup - (default false) set to true to open a zim Pane (blob.pane) with the points in a zim TextArea (blob.textArea) (click off to close)
NOTE: the TextArea output uses JSON.stringify() - to add the points to the points parameter of the Blob use JSON.parse(output);
NOTE: using zog(JSON.stringify(blob.recordData()))... the console will remove the quotes from the controlTypes so those would have to be manually put back in before parse() will work
also see points property
setPoints(data) - sets the Blob points to the data from getPoints()
this does not remake the Blob but rather shifts the controls so the number of points should be the same
also see points property
changeControl(index, type, rect1X, rect1Y, rect2X, rect2Y, circleX, circleY, update) - change a control type and properties at an index
accepts ZIM DUO normal parameters or configuration object literal with parameter names as propterties
passing in null as the index will change all points to the specified properties
the update parameter defaults to false so set to true to show update or call update() below
this is so multiple changes can be batched before calling update - for instance when animating blobs.
transformPoints(transformType, amount, x, y, approximateBounds) - scale, rotate, move points without affecting controls or borderWidth - returns object for chaining
transformType - String any of: "scale", "scaleX", "scaleY", "rotation", "x", "y"
amount - the amount to transform
x, y - (default 0, 0) the x and y position to transform about
approximateBounds defaults to true - set to false to not call approximateBounds after transforming points
reversePoints(sameStart) - reverse the order of the points
sameStart defaults to true and will keep the start point the same
set to false to make the last point before the start point, the start point
This also swaps each rectangle in the Bezier controls
also see the Code module for reversePoint(points) function to operate on data points in Squiggle format
Note: reversing blob points with the reversePoints function will make the starting point the last point
makeSquiggle(index) - create a new Squiggle by cutting blob at index (default 0)
returns the new Squiggle - the blob remains unchanged - so may need to remove it
splitBlob(a, b, num, clean) - split a Blob into two blobs - returns an array with each blob
this uses makeSquiggle() then splitPoints() to split squiggle then makeBlob() to make two blobs
a - (default 0) an index of the blob - or an object with an x and y property (read globally)
note - if using x, y points, these points do not have to be on the Blob - and they are global
b - (default Math.ceil(num points / 2)) an index of the blob - or an object with an x and y property (read globally)
num - (default 50) if points are used, this is how many points to add along the line between points to estimate cut point
clean - (default true) remove original blob - set to false to not remove
update(normalize) - update the Blob if animating control points, etc. would do this in a Ticker
set normalize (default false) to true to use pointsAdjusted for rotated and scaled points
use true for manually editing points after setting rotation or scale on point
just leave out if only animating points
showControls() - shows the controls (and returns blob) - or use blob.controlsVisible = true property
hideControls() - hides the controls (and returns blob) - or use blob.controlsVisible = false property
toggle(state - default null) - shows controls if hidden and hides controls if showing (returns the object for chaining)
or pass in true to show controls or false to hide controls
traverse(obj, start, end, time) - animates obj from start point to end point along path - thanks KV for the thought!
set start point greater than end point to traverse backwards
will dispatch a "traversed" event when done
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
getPointAngle(index) - gets the angle made by the tangent at the index provided
getSegmentPoint(point1, point2) - returns an array of [point1, controlPoint1, controlPoint2, point2]
used internally for animating to path and adding removing Bezier points
getAdjacentSegmentData(index) - returns an array of two arrays:
The first is an array of cubic Bezier points for segments adjacent and including the provided point index
each element is in the form of [point1, controlPoint1, controlPoint2, point2]
The second is an array of starting point indexes for the segments that were tested
used internally to drag an animation along the path
will wrap around the blob if needed
getCurvePoint(ratio, segmentRatios, segmentPoints, getAngle) gets a point along whole curve at the ratio (0-1) provided
along with x and y values, the point has a z value that is the index of the blob point before the calculated point
if the getAngle parameter is true (default false) the point also has an angle property which is the angle of the tangent at the point
ratio is 0-1 with 0 being at the first point and 1 being at the end of the last segment (the first point)
segmentRatios and segmentPoints will be calculated if not provided
used internally for animating along the path - if lockControls is true, only animate will precalculate these values
linearGradient([colors],[ratios], x0,y0, x1,y1) - shortcut to colorCommand linearGradient method (see properties below)
radialGradient([colors],[ratios], x0,y0,radius0, x1,y1,radius1) - shortcut to colorCommand radialGradient method (see properties below)
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact, commands) - makes a copy of the object
exact (default false)
ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
commands (default false) makes clones with current color commands of object
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - gives access to the shape of the blob
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
colorCommand - access to the CreateJS fill command for bitmap, linearGradient and radialGradient fills
eg. shape.colorCommand.linearGradient([green, blue ,green], [.2, .5, .8], 0, 0, shape.width, 0)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Fill.html
borderColor - get and set the stroke color
borderColorCommand - access to the CreateJS stroke command for bitmap, linearGradient and radialGradient strokes
See: https://www.createjs.com/docs/easeljs/classes/Graphics.Stroke.html
borderWidth - get and set the stroke size in pixels
borderWidthCommand - access to the CreateJS stroke style command (width, caps, joints, miter, ignoreScale)
See: https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeStyle.html
dashed - get and set the dashed - use true / false or an array (see dashed parameter)
dashedOffset - get and set the offset of the dash (50 default) - can animate this property for a marquee effect
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
circleColor - get or set the circle color of the controls - requires an update() to see changes
circleBorderColor - get or set the circle borderColor of the controls - requires an update() to see changes
stickColor - get or set the stick color of the controls - requires an update() to see changes
points - get or set the points array of the Blob in the same format as the points parameter:
a number, a shape string ("circle", "rectangle", "triangle"), a ZIM Circle, Rectangle, Triangle
or an array as follows:
[[controlX, controlY, circleX, circleY, rect1X, rect1Y, rect2X, rect2Y, controlType], [etc]]
see also getPoints(popup) and setPoints() methods
pointsAdjusted - get points with any point rotation converted to 0 - see update(true)
pointControls - get an array of controls (a container) - use this to animate controls
pointCircles - get an array of control circles - use this to place some other object at the point
pointObjects - get an array of point objects for each point in the following format:
[[control, circle, rect1, rect2, controlType], [etc.]]
control - the container for the control that holds the circle and rectangles (also see pointControls)
circle - the control point circle (also see pointCircles)
rect1 - the first control point rectangle
rect2 - the second control point rectangle
controlType - the control type: default is "straight" (or null) and there is also "mirror", "free" and "none"
NOTE: control, circle, rect1, rect2 can be positioned or animated and controlType can be changed
NOTE: the update() method must be called if manually changing the control positions or type
NOTE: if constantly animating the controls then use a Ticker.add(function(){blob.update();})
NOTE: also see recordData(), setData(), getPoints(), setPoints() methods for further options
addPointFactor - (default 20) used when placing new points along edge (editPoints is true)
divides the distance between points by this amount - the smaller the more accurate but also slower
addMinDistance - (default 15) edge press needs to be within this distance to add a point to the edge
segmentPoints - a read-only array of cubic Bezier points for each segment
each element is in the form of [point1, controlPoint1, controlPoint2, point2]
used internally to animate to the path and add and remove Bezier points
segmentRatios - a read-only array of cumulative ratio lengths of segments
for instance the default four points is [.25, .5, .75, 1]
used internally to animate to the path and attribute proportional time to each segment
controls - access to the container that holds the sets of controls
each control is given a read-only num property
sticks - access to the Shape that has the control sticks
lastSelected - access to the last selected (or created) control container
lastindex - the index number of the last selected controls
controlsVisible - get or set the visibility of the controls - or use showControls() and hideControls()
types - get or set the general array for the types ["mirror", "straight", "free", "none"]
changing this or removing a type will adjust the order when the user double clicks the points to change their type
this is not an array of types for each point - see the points property to access the types of each point
lockControls - Boolean to lock controls from being adjusted or not
allowToggle - Boolean to get or set clicking to show and hide controls
move - Boolean to drag or not drag Blob when controls are showing
can also set to "always" to allow movement when controls are not showing
lockControlType - Boolean to lock the type of the controls in their current state or not
onTop - get or set the onTop property
selectPoints - get or set whether points can be selected
interactive - get or set whether the shape is interactive - toggle, move, change or add controls, etc.
keyFocus - get or set the keyboard focus on the DisplayObject - see also zim.KEYFOCUS
will be set to true if this DisplayObject is the first made or DisplayObject is the last to be used with keyboard
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event for when the bezier controls are adjusted (pressup only or moving with keys - thanks Yui Kim for find)
if monitoring constant change is needed add a pressmove event to Blob.sets
the change event object has a transformType property with values of "move", "bezierPoint", "bezierHandle", "bezierSwitch"
dispatches "controlsshow" and "controlshide" events when clicked off and on and toggle is true
dispatches an "update" event if the points are changed or a point is added or removed
this removes all listeners on the old shape and controls
so any custom listeners on shape and controls will need to be re-applied - use the update event to do so
dispatches a "traversed" event when traverse() is done - the event object has an obj property for the traversing object
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤TOUR😊VIDS
Flare
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a flare shape - a shape with a gradual widening like flared pants or skirts.
The shape defaults to a horizontal rectangle flared outwardly to the right.
The flare angleA and angleB can be specified at any angle negative or positive.
The flare axis or spine can be at any angle to the horizontal positive in the x.
The cross or end angles can be specified relative to a normal the spine so 0 is -90.
Different color and border options are available and editable as properties.
More than one flare can be created in the same shape - these are called segments.
Multiple Flare objects can be easily combined into a ZIM MultiFlare
and a special FlareBox can be used to place flares or multiFlares around a rectangle
to be used for backings on buttons, pictures, etc.
See https://zimjs.com/ten/flare.html for examples of a 3D wall, a rocket and a button frame
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Flare().center();
// a Rocket
const rocket = new Flare({
thickness:100,
angles:-90, // all segment angles will point up
lengths:[40,.5,100,150,105],
anglesA:[-20,89,-12,0,-22], // anglesB will be mirrored by default
color:new GradientColor([dark,silver,dark],[.1,.6,.9],-50,0,50,0),
cross:true // add a line at segment borders
}).center();
// see also MultiFlare and FlareBox examples
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
color - (default black) the color of the flare
if null and a border is speficied the color will be transparent
borderColor - (default null) the stroke color
borderWidth - (default 1 if stroke is set) the size of the stroke in pixels
crossAngle - (default 0) the angle from the normal of the spine
so if the spine goes to the right at 0 degrees then 0 crossAngle starts at -90 and goes positive clockwise
a crossAangle of -45 would look like a picture frame bevel
if the flare starts at the top left corner of a rectangle
thickness - (default 20) the thickness at the start of the flare assuming 0 crossAngle
this will be divided evenly to thicknessA on one side of the spine and thicknessB on the other side of the spine
thicknessA - (default null) - will be set to half the thickness if thicknessB is not set otherwise thickness-thicknessB
thicknessB - (default null) - will be set to half the thickness if thicknessA is not set otherwise thickness-thicknessA
pin - (default null) - set to a segment number to set registration point at the start of the segment
Pin is used with MultiFlare to align flares at pinned segments
Pin is used with FlareBox to place pinned segments at any of the four corners of the box
When doing so, the Flare will be automatically rotated (corner number - pin number) * 90
This can be overriden by rotating the flare to the desired rotation after creation
startX - (default 0) shift the start of the flare in the x from the registration point (note, pin will reset registration)
startY - (default 0) shift the start of the flare in the y from the registration point (note, pin will reset registration)
lengths - (default [200]) an array of spine lengths
angles - (default [0]) an array of angles (degrees) for the spines relative to 0 along the positive x axis
anglesA - (default [10]) an array of relative angles to the left of the current spine when heading along the spine
so if the spine heads to the right, angleA is positive from the spine upwards
think of these as how much the shape flares out from the spine on one side
anglesB - (default anglesA) an array of relative angles to the right of the current spine when heading along the spine
so if the spine heads to the right, angleB is positive from the spine downwards
think of these as how much the shape flares out from the spine on another side
anglesEnd - (default [0]) an array of angles at the end of each segment from the normal of each segment spine
so if the spine goes to the right at 0 degrees then a 0 anglesEnd is perpendicular to the spine
an anglesEnd of 45 would look like a picture frame bevel
as the segments are placed around the picture frame clockwise
note: end angles greatly change the look of flared segments
poorly chosen angles can lead to flares crossing or massively diverging
good choices depend on the length of the flares, the spine angles and the flare angles
generally, a trial and error technique is the easiest to find the desired solution
cross - (default true) draw a crossing line at each segment - this draws each segment as a closed path
crossColors - (default null) an array of colors for each segment if cross is true
close - (default false) join the end of the last segment to the start of the first segment
dashed - (default false) set the dashed of the border if the borderColor or borderWidth is specified
strokeObj - (default {caps:"butt", joints:"miter", miterLimit:2, ignoreScale:false}) set to adjust stroke properties
caps options: "butt", "round", "square" or 0,1,2
joints options: "miter", "round", "bevel" or 0,1,2
miterLimit is the ration at which the mitered joint will be clipped
ignoreScale set to true will draw the specified line thickness regardless of object scale
spineColor - (default null) as the spine is drawn, fill the shape it makes with this color
this can create a picture frame effect as the spine color may hide half the flare for each segment
spineBorderWidth - (default null) the width of the spine
spineBorderColor - (default null) the color of the actual spine
spineDashed - (default false) set to true for dashed spine (if spineBorderWidth or spineBorderColor set)
spineStrokeObj - (default strokeObject) see strokeObject parameter for details
closeColor - (default color) the color of the segment created if closing the flare
closeBorderWidth - (default borderWidth) the borderWidth of the closing segment if closing the flare
closeBorderColor - (default borderColor) the borderColor of the closing segment if closing the flare
closeDashed - (default false) set to true for dashed closed segment (if closeBorderWidth or closeBorderColor set)
closeStrokeObj - (default strokeObject) see strokeObject parameter for details
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(lengths, angles, anglesA, anglesB, anglesEnd, cross, crossColors, close) |ZIM DUO| - add segment(s) to the Flare - returns object for chaining
see segment parameters for details - returns object for chaining
remake() - remake the Flare segments after setting properties
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy of the shape
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
shape - access to the ZIM Shape for the flare(s)
spineShape - access to the ZIM Shape for the spine if spine is true
closeShape - access to the ZIM Shape for the closing segment if close is true
pin - get or set the pin number - which spine has the registration point
see the pin parameter for more details
points - access to array of flare shape points {x,y}
if not close - around outside then around inside
if close - around each segment
pinPoints - access to array of spine points {x,y} and then to final end spine point
color - get and set the fill color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
borderColor - get and set the stroke color
borderWidth - get and set the stroke size in pixels
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
closeColor - get and set the fill color of the close segment
closeBorderColor - get and set the stroke color of the close segment
closeBorderWidth - get and set the stroke size in pixels of the close segment
closeBorderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
spineColor - get and set the fill color of the spine shape
spineBorderColor - get and set the stroke color of the spine shape
spineBorderWidth - get and set the stroke size in pixels of the spine shape
spineBorderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
** the following properties can be read or changed
** if changed, the remake() method must be run to see changes
** see the Flare parameters for definitions
thicknessA - number
thicknessB - number
cross - boolean
close - boolean
lengths - array
angles - array
anglesA - array
anglesB - array
anglesEnd - array
crossColors - array
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
MultiFlare
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Joins multiple Flare objects in one container
at the pin points of the flares or end to end.
See also ZIM Flare and ZIM FlareBox.
NOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// a fan of legs with feet!
const flare = new Flare({lengths:[100,100,20,8],anglesA:[5,-5,60],anglesB:[5,-5,0]})
const multi = new MultiFlare().center();
loop(12, i=>{
multi.add(flare.rot(i*360/12))
});
// or prepare flares and angles ahead of time
const flares = [];
const angles = [];
loop(12, i=>{
flares.push(flare.clone());
angles.push(i*360/12);
});
new MultiFlare(flares, null, angles).center();
// a ring of beads using endToEnd
const flare = new Flare({crossAngle:-360/12, lengths:[50,20,5,20,50],anglesA:[5,60,0,-60,-5]})
const flares = [];
const angles = [];
loop(12, i=>{
flares.push(flare.clone());
angles.push(i*360/12);
});
new MultiFlare(flares, null, angles, true).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
flares - (default null) an array of ZIM Flares objects to add - also see add() method
pins - (default null) an array of pin indexes for the flares
pins will set the registration point for each flare at whatever segment matches the pin index
angles - (default null) an array angles for the flares
endToEnd - (default false) set to true to locate each first segment point of the flare at the last segment point of the last flare
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(flares) - add an array of flares or a single flare to MultiFlare
add() redraws the whole flare so for many, make an array to start and pass it in as an argument
remove(flares) - remove an array of flares or a single flare to MultiFlare
remove() redraws the whole flare so for many, make an array to start and pass it in as an argument
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy of the multiFlare cloning the flares too
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
** can get and change the following properties
** see the paremeters for details
** if properties are changed call the remake() method to update the MultiFlare
flares - array
pins - array
angles - array
endToEnd - boolean
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
FlareBox
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a Rectangle with ZIM Flare objects positioned around edges and corners.
Pass in an array of Flare objects or a MultiFlare
FlareBox places flares at specified corner indexes depending on flare pin index.
See also ZIM Flare and ZIM MultiFlare.
A FlareBox can be used as a backing and rollBacking for buttons and other components
to create exciting borders inspired by the tail lights of 2020 automibiles.
See: https://zimjs.com/ten/flare.htmlNOTE
mouseChildren is turned to false for all zim Shape containers.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const border1 = new Flare({
thickness:6,
angles:[0,90], // to the right then down
lengths:[60,90],
anglesA:[3,-1.5], // flare angles
anglesEnd:[45,0], // 0 is optional
color:white,
pin:1 // pin at flare corner
});
const border2 = new Flare({
thickness:25,
angles:[0,90], // to right then down
lengths:[50,50],
anglesA:[-2,2], // anglesB will mirror these if not provided
anglesEnd:[45],
color:dark,
pin:1 // pin at flare corner
});
// put both flares at left top corner 0
// they each have pin of 1 so
// the rotation is (0-1)*90 = -90 (counter clockwise)
// they were to the right and down
// now they are up and to the right
const flareBox = new FlareBox(220, 100, blue, dark, 3, [border1, border2], [0,0])
.centerReg();
// clone the flares for the rollover FlareBox
// put the first flare at corner 2
// the rotation becomes (2-1)*90 = 90 (clockwise)
// it was built to go to the right and down
// now it is going down and to the left
const flareBoxOver = new FlareBox(220, 100, green, dark, 3, [border1.clone(), border2.clone()], [2,0])
.centerReg({add:false});
// use the flareBoxes as backings
const button = new Button({
width:flareBox.width,
height:flareBox.height,
backing:flareBox,
rollBacking:flareBoxOver
}).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 220) the width of the rectangle about which the Flare objects are placed
this is a little larger than the ZIM Button default width
height - (default 80) the height of the rectangle about which the Flare objects are placed
this is a little larger than the ZIM Button default height
color - (default black) the fill color as any CSS color including "rgba()" for alpha fill (set a to 0 for tranparent fill)
borderColor - (default null) the stroke color
borderWidth - (default 1 if stroke is set) the size of the stroke in pixels
flares - (default null) an array of ZIM Flare objects or a single flare or a ZIM MultiFlare
corners - (default [0]) an array of corner indexes to place the pin points of the ZIM Flare objects
corner indexes are:
0 - LEFT TOP
1 - RIGHT TOP
2 - RIGHT BOTTOM
3 - LEFT BOTTOM
pins - (default null) an array of pins of the ZIM Flare objects
The pin index can be set on the Flare or through the MultiFlare or here in the FlareBox
The pin is also the registration point of the flare so the flare will be placed at the corner at its pin
FlareBox will also automatically rotate the flares with this formula:
flare.rotation = (corner-pin)*90
This formula allows for easy setting of angles on corners
See the Button at https://zimjs.com/ten/flare.html
This can be overridden by setting the flare rotation after the FlareBox is created
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for shape - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy of the flareBox and clone flares as well
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
multiFlare - gives access to the ZIM Multiflare object
this is made automatically by FlareBox if an array of flares was used
flares - an array of flares that belong to the multiFlare
backing - gives access to the rectangle backing shape
color - get and set the fill color of the backing shape
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the backing shape
for instance, shape.setColorRange(blue, pink) then shape.colorRange = .5
will set the color of the shape to half way between blue and pink
shape.animate({color:red}, 1); is a shortcut to animate the colorRange
shape.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
borderColor - get and set the stroke color
borderWidth - get and set the stroke size in pixels
borderDashedCommand - access to the CreateJS stroke dashed command (segments, offset)
see https://www.createjs.com/docs/easeljs/classes/Graphics.StrokeDash.html
mouseChildren - set to false to avoid dragging the shape inside
to drag or interact with objects inside then set mouseChildren to true
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Label
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a label - wraps the createjs Text object.
Can use with Button, CheckBox, RadioButtons and Pane.
Text seems to come in different sizes so we do our best.
Have tended to find that left and alphabetic are most consistent across browsers.
Custom fonts loaded through css can be used as well.
NOTE
can wrap text at given width using lineWidth (or labelWidth) parameter.
To dynamically change the width without changing the font size use the labelWidth property.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Label("Hello").center(); // adds label to and centers on the stage
new Label({
text:"CLICK",
size:100,
font:"courier",
color:white,
rollColor:red,
bold:true,
italic:true
}).loc(100,100).tap(()=>{zog("tapping");});
EXAMPLE
// with text that wraps at labelWidth
// can also set this as a property later to dynamically change width of text
// without changing the size
new Label({
text:"this is a long bunch of text, this is a long bunch of text, this is a long bunch of text",
labelWidth:200
}).center();
EXAMPLE
STYLE = {font:"courier"};
new Label("Hi Courier").center(); // will be courier not arial
STYLE = {text:"YAY!", color:red};
new Label().center().mov(0,100); // will say YAY! in red arial font
new Label("Hello").center().mov(0,200); // will say Hello in red arial
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
text - |ZIM VEE| String for the the text of the label
size - (default 36) the size of the font in pixels
font - (default arial) the font or list of fonts for the text
color - (default black) color of font (any CSS color)
rollColor - (default color) the rollover color of the font
shadowColor - (default -1) for no shadow - set to any css color to see
shadowBlur - (default 14) if shadow is present
align - ((default LEFT) text registration point alignment also CENTER/MIDDLE and RIGHT
set to START to align LEFT for ZIM DIR constant is "ltr" or RIGHT when DIR="rtl" - END is the opposite
valign - (default TOP) vertical registration point alignment alse CENTER/MIDDLE, BOTTOM
bold - (default false) set the font to bold - note: fontOptions has been removed as of ZIM Cat
italic - (default false) set the font to italic - note: fontOptions has been removed as of ZIM Cat
variant - (default false) set to true to set the font to "small-caps" - note: fontOptions has been removed as of ZIM Cat
lineWidth - (default false) for no wrapping (use \n) Can set to number for wrap
lineHeight - (default getMeasuredLineHeight) set to number to adjust line height
backing - (default null) a Display object for the backing of the label (eg. Shape, Bitmap, Container, Sprite)
the backing most likely should be centerReg() ie. backing:new Rectangle(200,50,yellow).centerReg()
see ZIM Pizzazz module for a fun set of Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
outlineColor - (default null - or black if outlineWidth set) - the color of the outline of the text
outlineWidth - (default null - or (size*.2) if outlineColor set) - the thickness of the outline of the text
backgroundColor - (default null) set to CSS color to add a rectangular color around the label
The background color will change size to match the text of the label
Note: the backgroundColor is different than a backing which can be any Display Object
and background parameters are ignored if a backing parameter is set
backgroundBorderColor - (default null) the background stroke color
backgroundBorderWidth - (default null) thickness of the background border
corner - (default 0) the round of corner of the background if there is one
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
backgroundDashed - (default null) set to true for dashed background border (if backgroundBorderColor or backgroundBorderWidth set)
padding - (default 10 if backgroundColor set) places the border this amount from text (see paddingH and paddingV)
padding parameters are ignored if there is no backgroundColor set (also ignored if a backing parameter is set)
paddingH - (default padding) places border out at top bottom
paddingV - (default padding) places border out at left and right
shiftH - |ZIM VEE| (default 0) move the label (CreateJS Text) inside the Label container horizontally
shiftV - |ZIM VEE| (default 0) move the label (CreateJS Text) inside the Label container vertically
rollPersist - (default false) set to true to maintain rollover stage as long as mousedown or press is activated (used by Buttons)
labelWidth - (default null) the same as the lineWidth - the text will wrap at the labelWidth (added to match labelHeight)
labelHeight - (default null) the height of the text - setting this will probably alter the font size - so the size parameter is overwritten
for labelHeight to work, the labelWidth must also be set
using labelWidth and labelHeight together allow you to fit as much text into specified width and height dimensions
maxSize - (default null) set to limit the font size when using labelWidth and labelHeight
splitWords - (default false) set to true when lineWidth > 0 to split words at the line width
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setColorRange(color1, color2) - set a color range for label - used by colorRange property - returns obj for chaining
if one color is used, the current color is used and color1 is the second color in the range
showRollColor(visible) - default true to show roll color (used internally)
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy with properties such as x, y, etc. also copied
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
label - references the CreateJS Text object of the label
text - references the text property of the CreateJS Text object
size - the font size of the Label (without px)
font - get or set the font of the text
bold - get or set the bold (boolean) of the font
italic - get or set the italic (boolean) of the font
variant - get or set the variant (boolean) of the font (true is "small-caps")
align - get or set the horizontal alignment of the text
valign - get or set the vertical alignment of the text
paddingH - read-only value for paddingH of label
note - no padding property - that gets split into paddingH and paddingV
paddingV - read-only value for paddingV of label
color - gets or sets the label text color (and the rollColor if they are the same to start)
colorOnly - gets or only sets the label color
backgroundColor - gets or sets the label background color
colorRange - if setColorRange() is used, the colorRange is a ratio (0-1) between the colors
setting the colorRange will change the color property of the label
for instance, label.setColorRange(blue, pink) then label.colorRange = .5
will set the color of the label to half way between blue and pink
label.animate({color:red}, 1); is a shortcut to animate the colorRange
label.wiggle("colorRange", .5, .2, .5, 1, 5) will wiggle the colorRange
rollColor - gets or sets the label rollover color
labelWidth - the width at which the text wraps
currently does not work well with labelHeight and backgroundColor
labelHeight - setting this and labelWidth will change the font size to fit within the specified dimensions
outlineLabel - reference to the outline CreateJS Text object if there is an outline
backing - access to backing object
background - access to background Rectangle if backgroundColor is set
enabled - default is true - set to false to disable
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
LabelOnPath
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a label along a path of a Squiggle or Blob - which can be interactive, fixed, toggled or hidden
A list of percentages for where the letters are can be provided to move around letters
See: https://zimjs.com/explore/labelonpath.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const lop = new LabelOnPath({
label:"Hello World",
// label:new Label({text:"JELLO JIGGLES!", size:50}),
// path:new Blob(),
// path:new Squiggle({
// color:lighter,
// thickness:4,
// points:[[0,75,0,0,-100,200,100,-200],[300,75,0,0,-100,200,100,-200]]
// }).transformPoints("scaleX",2).transformPoints("rotation",0),
percentAngle:100, // default
showPath:false, // default
allowToggle:true, // default
interactive:true, // default
onTop:false // default
}).center();
zog(lop.text)
F.on("keydown", ()=>{
// shows percent spacing of letters along path
// could pass [results] in as an array to percents parameter of LabelOnPath
zog(lop.percents.toString());
// uncomment to record the path
// could pass this in as the points parameter to start with a given path
// lop.path.getPoints(true);
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
label - (default "Label on Path") a String or a ZIM Label
can set any label properties such as color, size, font, etc. on the label passed in
path - (default new Squiggle()) a ZIM Squiggle or ZIM Blob
can set any properties such as color, points, etc. on the shape passed in
percentAngle - (default 100) from 0-100 (or beyond in either direction) as to how much to tilt the letters
percents - (default null) an array of percentage locations of the letters along the line - should match number of letters
showPath - (default true) Boolean to show path at start
allowToggle - (default true) Boolean to allow user to toggle path off and on
interactive - (default true) Boolean to allow user to change path with controls, drag or add and remove points
can also set these individually on the path
onTop - (default false) - Boolean to set path on top when dragged
rtl - (default DIR) - set to true to start letters at right end of path - will just reverse the Blob or Squiggle path.
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
toggle(state) - leave off state to toggle path to opposite state. Use true to hide and false to show - returns object for chaining
hidePath() - hides path - returns object for chaining
showPath() - shows path - returns object for chaining
setProps(properties) - sets provided properties (as {prop:val, prop:val}) for each letter
the values accept ZIM VEE - dynamic parameters - see ZIM Pick()
returns object for chaining
resize() - if not interactive, call this to update the text on the path - returns object for chaining
cache(see Container docs for parameter description) - overrides CreateJS cache() and returns object for chaining
Leave parameters blank to cache bounds of shape (plus outer edge of border if borderWidth > 0)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - the name of the class as a String
text - get or set the text on the path
path - read-only access to path - but can manipulate the path
letters - access to ZIM Container of labels used for letters
for instance labels.loop(function (label) {label.color = red;});
or animate as a sequence labels.animate({props:{scale:1.5}, loop:true, rewind:true, sequence:200});
numLetters - how many letters - same as letters.numChildren
percents - access to the array of percents for letter positioning - resize() after changing unless interactive which auto resizes
color - get or set the color of the text
allowToggle - get or set the Boolean to allow toggling the path
interactive - get or set the Boolean to allow interaction with the path
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
LabelOnArc
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a label along an arc - see also LabelOnPath - for a more interactive version
Used internally for making labels on Radial and RadialMenu objects
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const loa = new LabelOnArc({
label:"Hello World"
}).center();
zog(loa.text);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
label - (default "Label on Arc") a String or a ZIM Label
can set any label properties such as color, size, font, etc. on the label passed in
size - (default 30) the font size of the label
font - (default "verdana") the font of the label - can load custom fonts in Frame() or F.loadAssets()
color - (default white) a color for the text can be any ZIM or CSS color
radius - (default 100) the radius of the circle to apply the arc of the text
flip - (default false) set to true to flip text if between 90 and 270
spacing - (default 0) the space between the Label and the arc - varies with different fonts
letterSpacing - (default 5) - the space between letters
angles - (default null) optionally specify an array of angles for the letters
this will override letterSpacing - see also angles property to receive an array of angles
showCircle - (default false) set to true to see a circle - then use circle property to adjust if desired
arcColor - (default null) set to a color to see a filled arc
arcBorderColor - (default null) the borderColor of the arc
acrBorderWidth - (default 2 if arcBorderColor) the borderWidth of the arc
radiusSpread - (default false) set to true to keep same letter angles as radius is changed
ignored if angles are provided
rtl - (default ZIM DIR) - set to true for right to left text
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
setProps(properties) - sets provided properties (as {prop:val, prop:val}) for each label
the values accept ZIM VEE - dynamic parameters - see ZIM Pick()
returns object for chaining
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - the name of the class as a String
text - get or set the text on the arc
radius - get or set the radius of the arc (see radiusSpread parameter too)
labels - an array of ZIM Label objects for the letters
letters - access to ZIM Container of labels used for letters
for instance labels.loop(function (label) {label.color = red;});
or animate as a sequence labels.animate({props:{scale:1.5}, loop:true, rewind:true, sequence:200});
numLetters - how many letters - same as letters.numChildren
letterHeight - get the height of letters
color - get or set the text color
circle - access to the circle object
arc - access to the arc object
angles - access to the array angles for letter positioning
use angles.toString() to log angle data (for kerning)
this can be modified and passed in as an angles property to start
innerRadius - the inside radius at the bottom of the text
outerRadius - the outside radius at the top of the text
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
LabelLetters
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Splits apart a ZIM Label into labels per characater
to allow manipulation of each character - animation, kerning, etc.
SEE: https://zimjs.com/ten/radial.html - (ZIM TEN) the title and subtitle
Also accepts basic HTML-like tags to allow Canvas text to have multi-formatting.
SEE: https://zimjs.com/cat/html.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const letters = new LabelLetters("Label Letters", CENTER, "bottom", 5)
.center()
.animate({
props:{scale:1.5, rotation:-10},
wait:.5,
time:.2,
sequence:.05,
rewind:true
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
label - (default "Label Letters") a String or a ZIM Label
can set any label properties such as color, size, font, etc. on the label passed in
can pass in a string with basic "old fashioned" HTML tags as follows:
<b>bold</b> - or <strong>bold</strong>
<i>italic</i> - or <em>italic</em>
<u>underline</u> - can use this with <a> to make a classic underlined link
<a href=url target=_blank>link</a>
<font
color=zimColor
backgroundColor='htmlColor'
rollBackgroundColor=#hexColor
size=20
family=verdana
group=groupStyle>font</font>
note: use NO QUOTES except for single quote with colors if want HTML blue for instance rather than ZIM blue
note: setting groupStyle will make letter from scratch as opposed to building on the submitted label styles
align - (default CENTER) set to LEFT, CENTER / MIDDLE, RIGHT for letter registration x positioning
also see lineAlign for alignment of lines
valign - (default CENTER) set to TOP, CENTER / MIDDLE, "bottom" for letter registration y positioning
also see lineValign for vertical alignment of lines
letterSpacing - (default 5) - the space between letters
letterSpacing is turned off if the Label has a backgroundColor
to use letterSpacing and a backgroundColor use the backing parameter of Label instead of backgroundColor
or use letterSpacings (see below) to set specific spacings (kerning) on letters
letterSpacings - (default null) - an array of the space between letters each letter
any value here will override the letterSpacing
0 is the index for the space between first and second letter
the length of this should be one less than the number of letters
lineSpacing - (default 5) - the space between lines (not including lineHeight)
lineSpacings - (default null) - an array of the space between lines
any values here will override the lineSpacing
lineHeight - (default null) null will auto set the height. Set to a number to force line heights - if \n or <br> are present in label
lineAlign - (default LEFT or RIGHT for rtl:true) the horizontal alignment of lines if multiple lines - set to LEFT, CENTER/MIDDLE, RIGHT
set to START to lineAlign LEFT for ZIM DIR constant is "ltr" or RIGHT when DIR="rtl" - END is the opposite
lineValign - (default BOTTOM) the vertical alignment within lineSpacing if multiple lines - set to TOP, CENTER/MIDDLE, BOTTOM
cache - (default false) set to true to cache each letter - improves performance on animation
rtl - (default false) set to true to reverse letters other than a-zA-Z0-9 and set default lineAlign to RIGHT
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
setProps(properties) - sets provided properties (as {prop:val, prop:val}) for each label
the values accept ZIM VEE - dynamic parameters - see ZIM Pick()
returns object for chaining
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - the name of the class as a String
text - get the text of the original Label
See: https://zimjs.com/zapp/Z_VSR9X for updating text
labels - an array of ZIM Label objects for the letters
numLetters - how many letters (same as numChildren)
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
LabelWords
zim class - extends a zim Wrapper which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Splits apart a ZIM Label into labels per word - also see LabelLetters
to allow manipulation of each word - animation, color, etc.
SEE: https://zimjs.com/016/labelwords.htmlNOTE
since this is really a Wrapper containing word Labels, all the wrapper functionality can be used.
SEE: https://zimjs.com/ten/wrapper.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new LabelWords({
label:"Here is LabelWords that divides text into words for individual control!",
color:white,
itemRegY:BOTTOM,
itemCache:true,
backgroundColor:series(red,orange,pink,green,blue,purple),
size:50,
width:700,
align:CENTER
}).center().mov(0,20).animate({
props:{scaleY:0},
time:.5,
rewind:true,
loop:true,
sequence:.1
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
label - (default "Will this wind...") a String or a ZIM Label
if custom Label properties beyond size, font, color, and backgroundColor are desired then pass in a ZIM Label
and LabelWords will clone the label to maintain letterSpacing, bold, italic, etc.
width - (default label width or 500) set to a width to set the width of the wrapper
size - |ZIM VEE| (default label size or 36) set the font size of the label
font - |ZIM VEE| (default label font or arial) set the font of the label
color - |ZIM VEE| (default label color or black) set the color of the label
backgroundColor - |ZIM VEE| (default label backgroundColor or null) set the background color of the label
itemRegX - |ZIM VEE| (default CENTER) the horizontal registration of the word Labels
itemRegY - |ZIM VEE| (default CENTER) the vertical registration of the word Labels
itemCache - (default false) set to true to cache each label - better for animation
spacingH - (default size/2) a spacing between items - ignored if colSize is set
spacingH does not get ZIM VEE - the results are jiggly when wrapping
spacingV - |ZIM VEE| (default size/2) a spacing between rows - ignored if rowSize is set
** WRAPPER PARAMETERS - we use the term wrapper to mean the LabelWords
** If using STYLE then style a Wrapper for these rather than LabelWords
wrapperType - (default "spacing") changes how the wrapper lays out the items as follows:
"spacing" - places each item spaced at the spacingH from the next item
"spread" - places equal spacing around edges and items horizontally (min the spacingH)
"stretch" - places equal spacing between objects horizontally with no spacing at edges (min the spacingH)
"column" - uses colSize parameter to determine spacing (spacingH is ignored)
align - |ZIM VEE| (default LEFT) set to CENTER, MIDDLE, RIGHT
this aligns the whole row - see also alignInner for aligning inside columns
align:series(LEFT, RIGHT) will toggle rows aligning left and right
valign - |ZIM VEE| (default TOP) set to CENTER, MIDDLE, BOTTOM
this aligns the rows at the top, middle or bottom only when a height is provided (rare)
see also valignInner for vertical aligning within rows (common)
alignInner - |ZIM VEE| (default LEFT) set to CENTER, MIDDLE, RIGHT
aligns the items when colSize is set only - see also align for aligning whole rows horizontally
valignInner - |ZIM VEE| (default BOTTOM) set to TOP, CENTER, MIDDLE
aligns the items in vertically in their row (common) - see also valign for aligning whole rows vertically (rare)
flip - |ZIM VEE| (default false) set to true to flip the order of the rows
flip:series(false, true) would read left to right then right to left then left to right, etc.
reverse - |ZIM VEE| (default false) set to true to reverse all the items so the first is (probably) at the bottom right
bottomFull - |ZIM VEE| (default false) set to true to fill the Wrapper at the bottom
does not reverse but rather leaves potentially fewer items at the top
colSize - |ZIM VEE| (default null) set to number to hard code column width
this is ignored if the wrapperType is not set to "column"
use colSize:series(100, 200, 100, 400) to set specific sizes
this will also the only setting for which alignInner works
rowSize - |ZIM VEE| (default null) set to number to hard code row height
this ignores spacingV but can be used with any wrapperType
use a series(100, 200, 100, 400) to set specific sizes
height - (default null) does not really set the height of the wrapper
the height is always determined by the width and the items as they wrap
(both the width and height cannot be used together without scaling and the wrapper does not scale items)
the height will have no effect when the valign parameter is set to TOP (default)
The height will place the bottom of the wrapper at the height when the valign is BOTTOM
The height will place the wrapper in the middle of the height when the valign is CENTER/MIDDLE
Note: in the all cases the bounds will still be the bounds around the wrapper
just the positioning of the wrapper is changed.
This allows the wrapper to be placed at the bottom and grow to the top
or placed in the middle and grow from the middle
which would not be possible otherwise aside from repositioning after each resize
minSpreadNum - (default 2) spread would always center a single item on a row
and can look weird spreading two or even three final items
a wrapper with wrapperType:"spread" will spread items if there are at least minSpreadNum items
if there is less than minSpreadItems then it will align the items according to align
minStretchNum - (default 3) stretch would always center a single item on a row
and can look weird stretching two or even three final items
a wrapper with wrapperType:"stretch" will stretch items if there are at least minStretchNum items
if there is less than minStretchItems then it will align the items according to align
this will not stop the first line from stretching unless minStretchFirst parameter is set to false
percentVoidH - |ZIM VEE| (default 0) set a percent horizontal space between items default in center
offsetVoidH - |ZIM VEE| (default 0) set a percent (or negative percent) to offset the void from the center horizontally
percentVoidV - |ZIM VEE| (default 0) set a percent vertical space between rows default in center
offsetVoidV - |ZIM VEE| (default 0) set a percent (or negative percent) to offset the void from the center vertically
minStretchFirst - (default true) set to false to avoid stretching the first line if less than minStretchNum is set and met
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
See ZIM Wrapper for methods such as setProps(), add(), addAt(), remove(), resize(), etc.
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - the name of the class as a String
text - get the text of the original Label
labels - an array of ZIM Label objects for the letters
numWords - how many words in labels (same as numChildren)
ALSO
see ZIM Wrapper for properties items, items2D, and properties for most of the Wrapper parameters
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Emoji
zim class - extends a zim.Label which extends a zim.Container
DESCRIPTION
Shows an emoji in a Label - an emoji is just text.
This helps treat the emoji as an image and works in conjunction with ZIM EmojiPicker
SEE: ZIM EmojiPicker() in COMPONENTS below ColorPicker().
SEE: https://zimjs.com/nft/bubbling/emoji.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// Go to https://emojipedia.org/ and find an emoji page
// copy the emoji or use the copy link and paste into the string below
new Emoji("paste the unicode icon here in string")
.center()
.drag();
EXAMPLE
// or use UTF code from https://zimjs.com/emoji
new Emoji("\ud83c\udf47") // grapes using UTF codes
.center()
.drag();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
code - |ZIM VEE| (default \ud83d\ude42") the Unicode Character or the Emoji from https://emojipedia.org/
or pass in UTF codes such as "\ud83d\ude42".
To convert from Unicode to UTF use https://zimjs.com/emoji/ (also see MORE link at bottom of page)
size - |ZIM VEE| (default 36) the size of the font in pixels
monochrome - (default false) set to true to make black outline - this is actually the bold version of the icon
italic - (default false) set the font to italic
** SEE Label for the rest of the definitions
backgroundColor, corner, backing, padding, paddingH, paddingV, shiftH, shiftV, style, group, inherit
backgroundColor - (default null) set to CSS color to add a rectangular color around the label
The background color will change size to match the text of the label
Note: the backgroundColor is different than a backing which can be any Display Object
and background parameters are ignored if a backing parameter is set
backgroundBorderColor - (default null) the background stroke color
backgroundBorderWidth - (default null) thickness of the background border
corner - (default 0) the round of corner of the background if there is one
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
backing - (default null) a Display object for the backing of the emoji (eg. Shape, Bitmap, Container, Sprite)
the backing most likely should be centerReg() ie. backing:new Rectangle(200,50,yellow).centerReg()
see ZIM Pizzazz module for a fun set of Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
padding - (default 10 if backgroundColor set) places the border this amount from emoji (see paddingH and paddingV)
padding parameters are ignored if there is no backgroundColor set (also ignored if a backing parameter is set)
paddingH - (default padding) places border out at top bottom
paddingV - (default padding) places border out at left and right
shiftH - (default 0) move the emoji inside the container horizontally
shiftV - (default 0) move the emoji inside the container vertically
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - the name of the class as a String
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Button
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes a button with rollover and many more features - see parameters.
You will need to pass in a Label to change the font properties of the button from the default.
You will then need to add the button to the stage and add a mousedown or click event.
Button rollover is done automatically.
Generally, there are three modes for a button - normal, toggle and wait.
Each of these have backgroundColor, color, backing and icon displays
and each of these have up (normal), roll and down states.
Down states were added in ZIM ZIM 01
SEE https://zimjs.com/zim/button.html
DISPLAYS FOR NORMAL MODE WITH THREE STATES EACH
backgroundColor, rollBackgroundColor, downBackgroundColor,
color, rollColor, downColor,
backing, rollBacking, downBacking,
icon, rollIcon, downIcon
** The normal mode also has borderColor, borderWidth, rollBorderColor and downBorderColor inserted after the color set.
The parameters are kept flat rather than grouped in {} object parameters in order to use ZIM DUO and STYLE
The button parameters have indicators showing the subsections
The normal mode is listed first, then general Button parameters such as corner, shadowColor, etc.
The toggle and wait parameters are listed last.
You can set a backing display object (Shape, Bitmap, Pattern, etc.) in place of the standard rectangle.
You can set an icon display object in place of the standard text
You can set the Button to toggle between text, backings or icons
SEE the ZIM Pizzazz series for a growing selection of backings, patterns and icons
https://zimjs.com/bits/view/pizzazz.htmlhttps://zimjs.com/bits/view/icons.htmlhttps://zimjs.com/patterns.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Button(200,60,"CLICK").center().tap(()=>{
zog("clicking");
});
// OR add custom label (needed to change label color for instance)
const label = new Label({
text:"POWER OPTION",
size:40,
backgroundColor:"violet",
bold:true
});
new Button({
label:label,
width:390,
height:110,
backgroundColor:"purple",
rollBackgroundColor:"MediumOrchid",
borderWidth:8,
borderColor:"violet",
gradient:.3,
corner:0
}).center();
EXAMPLE
// using the on() method and a mousedown - or click - event rather than tap()
// note - do not chain the on() method
const button = new Button().center();
button.on("mousedown", ()=>{
zgo("https://zimjs.com");
})
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
width - (default 200) the width of the button or AUTO to fit width to label (see also autoPadding)
height - (default 60) the height of the button or AUTO to fit height to label (see also autoPadding)
label - (default "CLICK" or "" if icon or backing) ZIM Label or plain text with default settings (white)
---------- NORMAL MODE
backgroundColor - |ZIM VEE| (default purple) background color of button (any CSS color)
also as of ZIM ZIM 01 any backgroundColor parameter can be written as bgColor
rollBackgroundColor - |ZIM VEE| (default backgroundColor.lighten(.2)) rollover background color of button
also as of ZIM ZIM 01 any backgroundColor parameter can be written as bgColor - so rollBgColor works, etc.
downBackgroundColor - |ZIM VEE| (default null) pressing down background color of button
color - |ZIM VEE| (default white) label color of button (any CSS color) unless a custom Label is set
rollColor - |ZIM VEE| (default white) rollover label color of button
downColor - |ZIM VEE| (default null) pressing down label color of button
borderColor - (default null) the color of the border
rollBorderColor - (default borderColor) rollover color of the border
downBorderColor - (default rollBorderColor) the pressing down color of the border
borderWidth - (default null) thickness of the border
backing - (default null) a Display object for the backing of the button (eg. Shape, Bitmap, Container, Sprite)
assumed to be center registration for easy positioning *** as with all backings
see ZIM Pizzazz module for a fun set of Button Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
https://zimjs.com/bits/view/pizzazz.html
rollBacking - (default null) a Display object for the backing of the rolled-on button
downBacking - (default null) a Display object for the backing of the pressed-down button
icon - (default null) set to display object to add icon at the center of the button and remove label
assumed to be center registration for easy positioning *** as with all icons
https://zimjs.com/bits/view/icons.html
rollIcon - (default null) set to display object to show icon on rollover
downIcon - (default null) set to display object to show icon on press down
---------- GENERAL PARAMETERS
corner - (default 10) the round of the corner (set to 0 for no corner)
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
and [horizontal, vertical] pairs - see Rectangle() for more info
dashed - (default false) set to true to turn the border to dashed - if the borderColor or borderWidth is provided
shadowColor - (default rgba(0,0,0,.3)) set to -1 for no shadow
shadowBlur - (default 14) how blurred the shadow is if the shadow is set
gradient - (default 0) 0 to 1 (try .3) adds a gradient to the button
gloss - (default 0) 0 to 1 (try .1) adds a gloss to the button
align - (default CENTER) horizontal align of the label
valign - (default CENTER) vertical align of the label
indent - (default 10) indent of label when align or valign is set
indentH - (default indent) horizontal indent of label when align or valign is set
indentV - (default indent) vertical indent of label when align or valign is set
hitPadding - (default 0) adds extra hit area to the button (good for mobile)
Note that if the button alpha is 0 the button will still be active if hitPadding is not equal to 0
Set the hitPadding property to 0 in this case - thanks Frank Los for the notice
autoPadding - (default 20) the padding used by AUTO width or height
autoPaddingH - (default autoPadding) the padding used by AUTO width
autoPaddingV - (default autoPadding) the padding used by AUTO height
rollPersist - (default false) set to true to keep rollover state when button is pressed even if rolling off
---------- TOGGLE MODE
toggle - (default null) set to string to toggle with label - or set to true to activate toggle but keep label the same
the button will not toggle if there is a wait parameter set
see also toggle colors, backings and icons
toggleBackgroundColor - (default backgroundColor) background color to make button when toggled
rollToggleBackgroundColor - (default toggleBackgroundColor) background color for button when toggled and rolled over
downToggleBackgroundColor - (default null) background color for button when toggled and pressed down
toggleColor - (default label's color) color to make text when toggled
rollToggleColor - (default label's roll color) color for text when toggled and rolled over
downToggleColor - (default null) color for text when toggled and pressed down
toggleBacking - (default null) set to display object to set a different backing for toggled state
rollToggleBacking - (default null) set to display object to set a backing for the rolled toggle state
downToggleBacking - (default null) set to display object to set a backing for the pressed down state
toggleIcon - (default null) set to display object to add icon at the center of the button and remove label in toggle state
rollToggleIcon - (default null) set to display object to show icon on rollover in toggle state
downToggleIcon - (default null) set to display object to show icon on press down in toggle state
toggleEvent - (default mousedown for mobile and click for not mobile) what event causes the toggle
---------- WAIT MODE
wait - (default null) - String word for button to show when button is pressed and a wait state is desired
LOADING: this can be used as a loading message - so change the button to "LOADING"
When the asset has loaded, use the clearWait() method to return to the normal button or toggled button state
CONFIRMING: this can also be used to confirm user action rather than a full new confirm panel
Set wait:"CONFIRM", set the waitBackgroundColor and rollWaitBackground parameters to red and the waitTime parameter to 4
In a button mousedown (must use mousedown - not click or tap if ACTIONEVENT is mousedown - the default),
check if the waiting property is true to test for confirmation
The waiting property will not be true for the first button press but will be true during the wait period
Perhaps set the waitModal parameter to true to clearWait() if the user clicks off the button
Use the clearWait() method to clear or cancel the wait status - for instance, if the pane the button is in is closed
waitTime - (default 5 seconds) seconds to show wait state before reverting to normal button (also see ZIM TIME constant)
waitBackgroundColor - (default red) background color to make button during wait time if wait is set
rollWaitBackgroundColor - (default rollBackgroundColor) background color for button when waiting and rolled over
downWaitBackgroundColor - (default null) background color for button when waiting and pressed down
waitColor - (default label's color) color to make text during wait time if wait is set
rollWaitColor - (default label's roll color) color for text when waiting and rolled over
downWaitColor - (default label's roll color) color for text when waiting and pressed down
waitBacking - (default null) set to display object to set a different backing for wait state
rollWaitBacking - (default null) set to display object to a different roll backing for wait state
downWaitBacking - (default null) set to display object to a different pressed-down backing for wait state
waitIcon - (default null) set to display object to add icon at the center of the button and remove label in wait state
rollWaitIcon - (default null) set to display object to show icon on rollover in wait state
downWaitIcon - (default null) set to display object to show icon on pressed down in wait state
waitModal - (default false) set to true to clearWait() if the user clicks off the button
waitEnabled - (default true) set to false to disable button while wait is in progress
---------- FINAL PARAMETERS
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setBacking(type, newBacking) - dynamically set any type of backing for button (if null removes backing for that type)
Backing types are: "backing", "rollBacking", "downBacking", "toggleBacking", "rollToggleBacking", "downToggleBacking", "waitBacking", "rollWaitBacking", "downWaitBacking"
note - all backing will have a pattern property if a pattern is set as a backing
setIcon(type, newIcon) - dynamically set any type of icon for button (if null removes icon for that type)
Icon types are: "icon", "rollIcon", "downIcon", "toggleIcon", "rollToggleIcon", "downToggleIcon", "waitIcon", "rollWaitIcon", "downWaitIcon"
toggle(state) - forces a toggle of label, backing and icon if set
state defaults to null so just toggles if left blank
pass in true to go to the toggled state and false to go to the original state
returns object for chaining
removeRoll() - force rollover state off
wait() - forces a wait state - with wait text, backings and icons if set
clearWait() - clears a wait state of the button - sets it back to normal
removeWait() - removes (and clears) a wait state of the button so it will not trigger again
hasProp(property as String) - returns true if property exists on object else returns false
clone(exact) - makes a copy with properties such as x, y, etc. also copied
exact - will ignore ZIM VEE values and clone the original values
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
text - references the text property of the Label object of the button
label - gives access to the label
color - get or set non-rolled on label color (if no icon specified)
rollColor - get or set rolled on label color
backgroundColor - get or set non-rolled on backing color (if no backing specified)
rollBackgroundColor - get or set rolled on backing color
rollPersist - default is false - set to true to keep rollover state when button is pressed even if rolling off
borderColor - get or set non-rolled on border color
rollBorderColor - get or set the border rolled color
hitPadding - extra padding for interactivity - see hitPadding parameter for extra notes
backing - references the backing of the button
use setBacking() to change as with all backings
note - all backings will have a pattern property if a pattern is set as a backing
rollBacking - references the rollBacking (if set)
downBacking - references the downBacking (if set)
icon - references the icon of the button (if set)
use setIcon() to change as with all icons
rollIcon - references the rollIcon (if set)
downIcon - references the downIcon (if set)
rolled - read-only true if button is being rolled over else false
pressed - read-only true if button is being pressed else false
toggled - read-only true if button is in toggled state, false if button is in original state
note: on mousedown toggle may not be switched over - except on mobile
so would recommend for consistency checking on click or tap or mouseup
toggleBacking - references the toggle backing (if set)
rollToggleBacking - references the toggle roll backing (if set)
downToggleBacking - references the toggle down backing (if set)
toggleIcon - references the toggle icon (if set)
rollToggleIcon - references the toggle roll icon (if set)
downToggleIcon - references the toggle down icon (if set)
waiting - read-only true if button is in the waiting state within wait time
note: must test this in a mousedown function not click or tap
waitBacking - references the wait backing (if set)
rollWaitBacking - references the wait roll backing (if set)
downWaitBacking - references the wait down backing (if set)
waitIcon - references the wait icon (if set)
rollWaitIcon - references the wait roll icon (if set)
downWaitIcon - references the wait down icon (if set)
focus - get or set the focus property of the Button used for tabOrder
enabled - default is true - set to false to disable
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
for example seeing toggle take effect
EVENTS
dispatches a "waited" event if button is in wait state and the wait time has completed
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
CheckBox
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A checkbox that when pressed toggles the check and a checked property.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const checkBox = new CheckBox(50, "TEST").center().change(()=>{
zog(checkBox.checked); // will be true then false, etc.
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
size - (default 60) size in pixels (always square)
label - |ZIM VEE| (default null) ZIM Label object - or String to make a default label (black)
startChecked - |ZIM VEE| (default false) an initial parameter to set checked if true
color - (default darker) the text color of the label
backgroundColor - (default white.toAlpha(.8)) the background color of the box
borderColor - (default darker) the color of the border
borderWidth - (default size/10) thickness of the border
corner - (default 0) the round of the corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
margin - (default 10) is on outside of box so clicking or pressing is easier
indicatorType - (default check) could be square (box) or x
indicatorColor - (default borderColor or black if no border) the color of the indicator
tap - (default false) set to true to tap to activate CheckBox rather than mousedown or click
rtl - (default DIR=="rtl") set to true to force CheckBox to the right of the text
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setChecked(Boolean) - defaults to true to set button checked (or use checked property)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
checked - gets or sets the check of the box
label - gives access to the label
text - the text of the label
box - the Rectangle of the checkBox
box2 - the border Rectangle of the checkBox
indicator - gives access to the check mark ie. indicator.sca(.8);
indicatorColor - get or set the color of the indicator
enabled - default is true - set to false to disable
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when pressed on but not when the checked property is set
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
RadioButtons
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A radio button set that lets you pick from choices.
Radio buttons can display radio buttons vertically (default) or horizontally.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const radioButtons = new RadioButtons(50, ["ONE", "TWO", "THREE"]).center().change(()=>{
zog(radioButtons.text); // will be ONE, TWO or THREE
zog(radioButtons.index); // will be 0, 1, or 2
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
size - (default 60) in pixels
buttons - an array of button data objects as follows:
[{label:ZIM Label or text, id:optional id, selected:optional Boolean}, {etc...}]
or just a list of labels for default labels ["hi", "bye", "what!"]
vertical - (default true) displays radio buttons vertically - set to false to display horizontally
color - (default darker) the text color of the label
backgroundColor - (default "rgba(255,255,255,.8)") the background color of the circle
borderColor - (default darker) the color of the border
borderWidth - (default size/9) thickness of the border
spacing - (size*.2 for vertical and size for horizontal) the space between radio button objects
margin - (size/5) the space around the radio button itself
always - (default true) if set false, cannot click on selection to unselect it
indicatorColor - (default borderColor or black) the color of the indicator
index - (default 0) - set the index at start
rtl - (default DIR=="rtl") - set to true to put text on left of RadioButtons
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setSelected(num) - sets the selected index (or use index) -1 is default (none)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
selected - gets the selected object - selected.label, selected.id, etc.
index - gets or sets the selected index of the buttons
label - current selected label object
text - current selected label text
id - current selected id
buttons - an array of button Container objects holding the shape and label (note - different than buttons parameter)
labels - an array of the ZIM Label objects. labels[0].text = "YUM"; labels[2].y -= 10;
indicators - an array of the zim Shape dot objects. indicators[0].color = "yellow";
enabled - default is true - set to false to disable
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when pressed but not when index is set
then ask for the properties above for info
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Toggle
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A Toggle button that toggles off and on - with optional labels
Thanks Andi Erni for the initial design and coding of the Toggle.
See: https://zimjs.com/explore/toggle.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const toggle = new Toggle({label:"ON"}).center().change(()=>{
zog(toggle.toggled);
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 80) the width of the toggle (less labels)
height - (default 50) the height of the toggle
label - (default null) an optional ZIM Label (or text for default label properties)
also see labelLeft for left side text
startToggled - (default false) set to true to start in the toggled position
backgroundColor - (default purple) set to any HTML color for background color
margin - (default 10) the distance around and between the toggle and its parts
indicatorType - (default "circle" or "round") set to "rectangle" or "square" for square indicator
indicatorColor - (default darker)
toggleBackgroundColor - (default "#F93") orange - for toggled background color
try setting the borderColor to the same color as the background for inner color change effect
color - (default darker) the font color of the toggle
borderColor - (default null) the color of the border
borderWidth - (default null - or 1 if borderColor) the size of the border
corner - (default half the height) a corner radius - or an array of corners [topLeft, topRight, bottomRight, bottomLeft]
indicatorCorner - (default 0) change the corner radius of a rectangle toggleType - or an array of corners [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default "rgba(0,0,0,.3)" if shadowBlur) the shadow color - set to -1 for no shadow
shadowBlur - (default 14 if shadowColor) the shadow blur - set to -1 for no shadow
time - (default .1) time in seconds for toggle to animate (also see ZIM TIME constant)
labelLeft - (default null) an optional ZIM Label for the left side of the toggle (or text for default label properties)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
toggle(state) - toggle the toggle - state defaults to true - set to false to un-toggle
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
toggled - gets and sets the toggled state of the toggle
text - gets the selected label text or "on" / "off" if no label
indicator - access to the indicator object
background - access to background Rectangle
label - access to the label if provided
labelLeft - access to the label on the left if provided
enabled - default is true - set to false to disable
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event when pressed but not when toggle() is used
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Tip
zim class - extends a a zim.Label which extends a zim.Container which extends a createjs.Container
DESCRIPTION
A Tip() can be used to show some extra information - the tip disappears after an amount of time
Tip has easy positioning along the inside edges or the outside edges of a target.
NOTE
Tip places the tip on the stage when the show() method is called
You can reposition with .mov() etc. if desired
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Tip("Press Circle").show(1); // wait one second and show tip at 40 pixels from bottom right
const circle = new Circle().center().tap(()=>{
circleTip.show();
});
const circleTip = new Tip({
text:"This is a default ZIM Circle",
backgroundColor:white,
color:black,
outside:true, // outside the circle
target:circle,
align:CENTER,
valign:BOTTOM,
margin:14,
corner:0,
size:20
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
text - (default "Here's a tip!") String for the the text of the tip
tipAlign - (default RIGHT) the horizontal position of the tip (LEFT, CENTER / MIDDLE, RIGHT)
tipValign - (default BOTTOM") the vertical position of the tip (TOP, CENTER / MIDDLE, BOTTOM")
margin - (default 40) distance from side (unless centered) in pixels
marginH - (default margin) distance from horizontal edges
marginV - (default margin) distance from vertical edges
outside - (default false) set to true to place Tip on outside of container
target - (default zdf's stage) tip is placed on stage relative to container
delay - (default 0) set the default delay for show() - can override with show() parameters
time - (default 2) set the default time for show() - can override with show() parameters
mouseClose - (default true) set to false to not hide tip on mouse press
** the rest are parameters for a Label (align and valign are set as textAlign and textValign)
size - (default 36) the size of the font in pixels
font - (default arial) the font or list of fonts for the text
color - (default black) color of font (any CSS color)
rollColor - (default color) the rollover color of the font
shadowColor - (default "rgba(0,0,0,.3)") set to -1 for no shadow - set to any css color to see
shadowBlur - (default 1) if shadow is present
align - ((default LEFT) text registration point alignment also CENTER and RIGHT
valign - (default CENTER) vertical registration point alignment alse MIDDLE / CENTER, BOTTOM
lineWidth - (default false) for no wrapping (use \n) Can set to number for wrap
lineHeight - (default getMeasuredLineHeight) set to number to adjust line height
backing - (default null) a Display object for the backing of the label (eg. Shape, Bitmap, Container, Sprite)
see ZIM Pizzazz module for a fun set of Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
outlineColor - (default null - or black if outlineWidth set) - the color of the outline of the text
outlineWidth - (default null - or (size*.2) if outlineColor set) - the thickness of the outline of the text
backgroundColor - (default null) set to CSS color to add a rectangular color around the label
The background color will change size to match the text of the label
Note: the backgroundColor is different than a backing which can be any Display Object
and background parameters are ignored if a backing parameter is set
backgroundBorderColor - (default null) the background stroke color
backgroundBorderWidth - (default null) thickness of the background border
corner - (default 0) the round of corner of the background if there is one
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
backgroundDashed - (default null) set to true for dashed background border (if backgroundBorderColor or backgroundBorderWidth set)
padding - (default 10 if backgroundColor set) places the border this amount from text (see paddingH and paddingV)
padding parameters are ignored if there is no backgroundColor set (also ignored if a backing parameter is set)
paddingH - (default padding) places border out at top bottom
paddingV - (default padding) places border out at left and right
shiftH - (default 0) move the label (CreateJS Text) inside the Label container horizontally
shiftV - (default 0) move the label (CreateJS Text) inside the Label container vertically
rollPersist - (default false) set to true to maintain rollover stage as long as mousedown or press is activated (used by Buttons)
labelWidth - (default null) the same as the lineWidth - the text will wrap at the labelWidth (added to match labelHeight)
labelHeight - (default null) the height of the text - setting this will probably alter the font size - so the size parameter is overwritten
for labelHeight to work, the labelWidth must also be set
using labelWidth and labelHeight together allow you to fit as much text into specified width and height dimensions
maxSize - (default null) set to limit the font size when using labelWidth and labelHeight
bold - (default false) set to true to bold the tip
italic - (default false) set to true to italic the tip
variant - (default false) set to true to set the tip to small caps
splitWords - (default false) set to true to split words when wrapping
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show(delay, time) - show the tip - delay in s defaults to 0 and time in s defaults to 2 (also see ZIM TIME constant)
default delay and time can be set with main default and time parameters for Tip()
hide() - hides tip - show() will also hide the tip automatically after the time provided
clear() - hides tip and removes the call to a delayed tip using a delay time in show()
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
see all methods of a Label() such as setColorRange(), etc.
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
tipAlign - get or set the horizontal alignment of the tip
tipValign - get or set the vertical alignment of the tip
text - get or set the text of the Tip
ALSO
see all properties of a Label() such as size, color, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Pane
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Adds a window for alerts, etc.
You need to call the pane.show() to show the pane and pane.hide() to hide it.
You do not need to add it to the stage - it adds itself centered.
You can change the x and y (the origin and registration point are in the middle).
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
new Pane("Watch out!", yellow).show(); // pressing anywhere will close pane (see parameters for options)
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
// NOTE: do not use the on("close", f) method as it will not receive an event
// with keyboardAccess the events on the canvas are turned off and captured in an any iFrame
new Pane({content:"START", keyboardAccess:true}).show(()=>{zog("Keys ready")});
EXAMPLE
const pane = new Pane({width:600, height:250, modal:false, displayClose:false});
const cancel = new Button(220, 100, "CANCEL", red).center(pane).mov(-130);
const confirm = new Button(220, 100, "CONFIRM", green).center(pane).mov(130);
cancel.on("click", ()=>{pane.hide();});
confirm.on("click", ()=>{zgo("https://zimjs.com")});
pane.show(); // pressing anywhere will close pane (see parameters for options)
EXAMPLE
// as above but using a callback function in show()
const pane = new Pane({width:600, height:250, modal:false, displayClose:false}).show(confirm=>{
if (confirm) zgo("https://zimjs.com");
});
const cancel = new Button(220, 100, "CANCEL", red).center(pane).mov(-130).tap(()=>{
pane.hide(false);
});
const confirm = new Button(220, 100, "CONFIRM", green).center(pane).mov(130).tap(()=>{
pane.hide(true);
});
EXAMPLE
// as above but using CONTENT CONFIG OBJECT
const pane = new Pane({
width:600,
height:250,
modal:false,
displayClose:false,
content:{
buttonScale:1,
buttons:[
{
label:"CANCEL",
bgColor:red,
call:()=>{pane.hide();}
}, {
label:"CONFIRM",
bgColor:green,
call:()=>{zgo("https://zimjs.com");}
}
]
}
}).show();
EXAMPLE
// custom backing with ZIM Pizzazz import at top
// import zim from "https://zimjs.org/cdn/016/zim_pizzazz"
new Pane({
content:new Label({color:white, text:"STOP", size:50}),
backing:makePattern({
type:"stripes",
colors:series(red,black),
rows:20
}).alp(.8)
}).show();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
content - (default " ") optional content to be centered in one of three formats:
a string or number to add a ZIM Label - color darker
a ZIM DisplayObject such as a Circle or a Container with more objects, etc.
a content configuration object {} with the following properties - any are optional:
header - a ZIM DisplayObject for the top of the content
message - text that will put into a ZIM Label - default darker - see color property
display - a ZIM DisplayObject for beneath the message
buttons - an array of ZIM Button objects or configuration objects {} as follows:
{label, color, rollColor, backgroundColor, rollBackgroundColor, call}
with call being a callback function for when the button is pressed
buttonScale - the scale for the buttons
color - the color of the message
spacingH - horizontal space between the buttons
spacingV - vertical space between the content areas
align - default CENTER, or use LEFT or RIGHT
backgroundColor - (default white) a css color for the background of the Pane
color - (default black) a css color for the text color of the Pane
width - (default AUTO) width of pane - AUTO will matches content width - see also autoPadding and autoPaddingH
height - (default AUTO) height of pane - AUTO will matches content width - see also autoPadding and autoPaddingV
draggable - (default false) pass in true to drag the pane
resets - (default true) resets position to start on re-open - set to false to keep last position
modal - (default true) pane will close when user clicks off the pane - set to false to keep pane open
corner - (default 20) is the corner radius - set to 0 for no corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
backdropColor - (default "rgba(0,0,0,.2)") the color of the background that fills the stage
shadowColor - (default "rgba(0,0,0,.3)") set to -1 for no shadow
shadowBlur - (default 20) how blurred the shadow is if shadow is set
center - (default true) centers the pane
if center is false you will have to set x and y for the pane
the registration point and the origin inside the pane is in the center
you can adjust the label placement by changing its x and y or registration point
displayClose - (default true) closes the Pane if display backing is pressed
if draggable is set to true, displayClose will automatically be set to false
backdropClose - (default true) closes the Pane if backdrop is pressed
backing - (default null) a Display object for the backing of the pane (eg. Shape, Bitmap, Container, Sprite)
see ZIM Pizzazz module for a fun set of Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
as well as patterned backings using Pizzazz 3
fadeTime - (default 0) seconds to fade in and out - also see ZIM TIME constant
container - (default - the default stage) container for the pane
titleBar - (default null - no titleBar) a String or ZIM Label title for the pane that will be presented on a titleBar across the top
titleBarColor - (default black) the color of the titleBar text if a titleBar is requested
titleBarBackgroundColor - (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - (default fit label) the height of the titleBar if a titleBar is requested
close - (default false) - a close X for the top right corner that closes the pane when pressed
closeColor - (default grey) - the color of the close X if close is requested
autoPadding - (default 70) the padding used by AUTO width or height
autoPaddingH - (default autoPadding) the padding used by AUTO width
autoPaddingV - (default autoPadding) the padding used by AUTO height
keyboardAccess - (default false) set to true to adds a click through iframe to gain keyboard control
this sets an invisible Frame keyboardMessage() that will close the pane and give key access to iFrames
do not use if expecting interactive content in the Pane - it is for a start message only
do not use on("close", f) as it will not be captured with keyboardAccess true
instead, use the callback in show() to call a function on close
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show(call, params) - shows the pane (returns the pane for chaining)
pass in an optional callback function that will be called when the pane closes
pass in an optional params object that will be passed to the callback when the pane closes
also see the closeCall and closeParams property to set these dynamically
for instance, if the pane has YES and NO buttons, the closeParams can be set to true or false
for easy results to an option pop-up
(as of ZIM ZIM 01 can also use pos(), loc(), center(), etc.)
hide(params, callEvent) - hides the pane
params will set the closeParams property that gets sent to a callback function in the show()
callEvent defaults to false - set to true to also call close event
(as of ZIM ZIM 01 can also use removeFrom())
toggle(state - default null) - shows if hidden and hides if showing (returns the pane for chaining)
or pass in true to show pane or false to hide pane
add(obj, index, center, replace) - supports DUO - add object to the content container with optional center
or just add content like usual to the contentContainer.
index is the level in the contentContainer - default is the top
center (default true) for Pane (different than Panel and Window which have false as default)
replace (default true) for Pane (different than Panel and Window which have false as default)
will replace the current content with the new content
see also content parameter of Pane and contentContainer property
returns the pane for chaining
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied (returns the new pane for chaining)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
closeCall - a function to call when the pane closes (see also call parameter of show method)
closeParams - an object to pass to the closeCall (see also params parameter of show method)
backing - or display - reference to the pane box
contentContainer - ZIM Container used to hold added content (formerly the content property)
use the add() method or add directly to the contentContainer property of the pane
content - gives access to the content provided as a parameter to the Pane()
** in the past, content refered to what is now the contentContainer
If a content config object {} is used, the following properties are added to the Pane()
header - reference to the header if provided
message - reference to the message if provided - this is a Label
text - reference to the text of the message if provided
display- reference to the display if provided
buttons - an array of the Button objects if provided
config - the original content config object {}
titleBar - gives access to the titleBar Container - which also has a background property
titleBarLabel - gives access to the titleBar label
toggled - read-only Boolean property as to whether pane is showing
close - access to the ZIM Shape if there is a close X
backdrop - reference to the backdrop that covers the stage
container - get or set the container the pane will be added to
resetX - if reset is true you can dynamically adjust the position if needed
resetY - and the y position for reset...
enabled - set to false to disable component
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "closing" event when about to be closed - good for reloading a game for instance
dispatches a "close" event when closed by clicking on backing, display, close, etc. when applicable
see also call and params parameters of show() plus closeCall and closeParams properties
see also params parameter of hide() which also sets the closeParams property
dispatches a "change" event when closed by clicking on backing, display, close, etc. when applicable
dispatches a "fadedin" event if fadeTime is set and pane has finished its fade in animation
dispatches a "fadedout" event if fadeTime is set and pane has finished its fade out animation
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Panel
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A simple panel with titleBar and optional arrow for more panels.
Panel can be set draggable and can have a collapse button and a close button
See: https://zimjs.com/explore/panel.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// make a panel with two pages
const panel = new Panel({titleBar:series("TODAY", "TOMORROW")})
.center();
// content for panel 1
const today = new Circle(30, yellow);
panel.add(today, 0, true); // content, level, center on content
// content for panel 2
const tomorrow = new Label("-30");
// event to change content as panels change
panel.on("change", ()=>{
if (today.parent) {
panel.add(tomorrow, 0, true, true); // content, level, center and replace
} else {
panel.add(today, 0, true, true); // content, level, center and replace
}
S.update();
});
EXAMPLE
const panel = new Panel({
width:400,
height:250,
bgColor:new GradientColor([black,dark],90),
titleBar:"CONTENT",
draggable:true,
content:{
message:"We shall greet you!",
color:lighter, // override default darker
display:new TextInput({placeholder:"enter name"}).sca(.7),
align:CENTER, // default
spacingV:25, // 20 is default
spacingH:10, // default
buttonScale:.5, // default
buttons:[ // or just a single button object
{
label:"GREET",
bgColor:new GradientColor([green,blue],90),
width:300,
call:()=>{
new Emitter({
obj:new Label("Hello "+panel.display.text, 80, null, [green,blue,orange,yellow,pink]),
startPaused:true,
shrink:false,
life:2,
gravity:2,
force:{min:2,max:6}
}).loc(panel).spurt(20).on("spurtfizzed",e=>{e.target.dispose();});
}
}, {
// button:new Button(), // can also specify a custom Button
label:"CLEAR",
bgColor:new GradientColor([yellow,orange],90),
call:()=>{panel.display.text="";}
}
]
}
}).centerReg();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 250) the width of the panel
height - (default 300) the height of the panel
content - (default null) optional content to be centered in one of three formats:
a string or number to add a ZIM Label - default white
a ZIM DisplayObject such as a Circle or a Container with more objects, etc.
a content configuration object {} with the following properties - any are optional:
header - a ZIM DisplayObject for the top of the content
message - text that will put into a ZIM Label - default color white - see color property
display - a ZIM DisplayObject for beneath the message
buttons - an array of ZIM Button objects or configuration objects {} as follows:
{label, color, rollColor, backgroundColor, rollBackgroundColor, call}
with call being a callback function for when the button is pressed
buttonScale - the scale for the buttons
color - the color of the message
spacingH - (default 20*buttonScale) horizontal space between the buttons
spacingV - (default 20) vertical space between the content areas
align - default CENTER, or use LEFT or RIGHT
titleBar - |ZIM VEE| (default "PANEL") a String or ZIM Label title for the panel that will be presented on a titleBar across the top
Panel must have a titleBar - use a Pane or a Rectangle if a titleBar is not desired.
titleBarColor - |ZIM VEE| (default black) the text color of the titleBar
titleBarBackgroundColor - |ZIM VEE| (default "rgba(0,0,0,.2)") the background color of the titleBar
titleBarHeight - (default fit label) the height of the titleBar
backgroundColor - |ZIM VEE| (default lighter) background color (use clear - or "rbga(0,0,0,0)" for no background)
borderColor - |ZIM VEE| (default pewter) border color
borderWidth - (default 1) the thickness of the border
corner - (default 5) the round of corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
close - (default false) - add a close icon top right
closeColor - (default titleBarColor) the color of the close icon
next - (default true if more than one panel) set to false to not show an next arrow if multiple panels
nextColor - (default titleBarColor) the color of the next icon
extraButton - (default null) creates a little square button with the letter R for reset
this is made with the group style id of "extraButton"
use the extraButton property to access the button to change its label or capture an event, etc.
collapse - (default false) - set to true to add a collapse icon to the titleBar that reduces the panel so only the bar shows and adds an icon to expand
also can double click bar to collapse panel
collapseColor - (default grey) - the color of the collapse icon
collapsed - (default false) set to true to start the panel collapsed
align - (default LEFT) set to CENTER, MIDDLE or "right" to align the label on the titleBar
this may get in the way of the close, arrow, collapse or extra buttons at right
shadowColor - (default "rgba(0,0,0,.3)" if shadowBlur) the shadow color - set to -1 for no shadow
shadowBlur - (default 14 if shadowColor) the shadow blur - set to -1 for no shadow
draggable - (default true if titleBar) set to false to not allow dragging titleBar to drag window
boundary - (default null) set to ZIM Boundary() object - or CreateJS.rectangle()
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(obj, index, center, replace) - supports DUO - add object to the content container with optional center
note that the content container is below the title bar
index is the level in the contentContainer - default is the top
replace will replace the current content with the new content
see also content parameter of Panel and contentContainer property
returns the panel for chaining
nextPanel(index, event) - show next panel - the panels are set up to be a series or random or function based
this means there is not necessarily an order to be able to go backwards to... so, only forward!
If a series is provided to the Panel title, etc. then the index can be used to go to the title in the series at the index
event (default false) will dispatch a change event if nextPanel is called
hasProp(property as String) - returns true if property exists on object else returns false
collapse(state) - state defaults to true to collapse or set to false to expand collapsed panel
must start with the collapse parameter set to true
also see collapsed property
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
contentContainer - ZIM Container used to hold added content (formerly the content property)
this is below the title bar - use the add() method or add directly to the contentContainer property of the panel
content - gives access to the content provided as a parameter to the Panel()
** in the past, content refered to what is now the contentContainer
If a content config object {} is used, the following properties are added to the Panel()
header - reference to the header if provided
message - reference to the message if provided - this is a Label
text - reference to the text of the message if provided
display- reference to the display if provided
buttons - an array of the Button objects if provided
config - the original content config object {}
panelHeight - get and set the height of the panel without scaling it as height does (for width, remake the Panel object)
titleBar - access to the titleBar container
label - access to the label of the current panel
text - access to the text of the current panel
titleBar - gives access to the titleBar Container - which also has a background property
titleBarLabel - gives access to the titleBar label
closeIcon - access to the close button
collapseIcon - access to the ZIM Shape if there is a collapse triangle
collapsed - get or set whether the panel is collapsed - must start with collapse parameter set to true
also see collapse() method
arrow - access to the next arrow
background - access to the background Rectangle
extraButton - access to the Label for the extra button if extraButton parameter is set to true
use this to set the text in the button (a one letter button is expected - for instance, i for info, R for reset, etc.)
overlay - access to the overlay Rectangle used if enabled = false
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
group - used when the object is made to add STYLE with the group selector (like a CSS class)
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event when arrow is pressed to go to the next panel
dispatches a "close" event when closed with close button if there is a close button
dispatches a "collapse" event if collapsing
dispatches a "expand" event if expanding after being collapsed
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Window
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Adds a window for content that can be swiped and scrolled.
NOTE
if zim namespace zns = true then this overwrites a JS Window - so the JS Window is stored as document.Window
NOTE
set the enable property to false if animating the position of the whole Window
then set the enable property to true on the animate call function. See update() method for more.
NOTE
to add ZIM Swipe() to objects in window set the overrideNoSwipe parameter of Swipe to true
NOTE
if animating the window off screen then either turn optimize:false
or use window.update() in the "animation" event with the animate({events:true})
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const w = new Window({scrollBarDrag:true, padding:20}).center();
const t = new Tile(new Circle(20, red), 4, 20, 20, 20);
w.add(t);
// the above would only drag on the circles (or the scrollbars)
// adding a Rectangle to help dragging
w.add(new Rectangle(w.width-20,t.height,dark), 0);
// or could have added it to the bottom of the Tile
// new Rectangle(w.width-20,t.height,dark).addTo(t).bot();
EXAMPLE
// Make two windows resize based on one resizeHandle
// We will use a List which extends a Window
// See https://zimjs.com/explore/splitter.html
const listWidth = 200;
const windowWidth = 600;
const margin = 50;
const list = new List({
width:listWidth+windowWidth,
align:LEFT,
scrollBarDrag:true,
resizeHandle:true,
resizeBoundary:new Boundary(-listWidth-windowWidth+margin,0,listWidth+windowWidth-margin*2, 0),
// resizeVisible:true
})
.resize(listWidth)
.pos(120,-80,LEFT,CENTER);
list.items[1].label.text = "Some very long but important option!";
list.on("resize", ()=>{
const point = list.resizeHandle.localToGlobal(0,0);
win.resize(list.x+listWidth+windowWidth-point.x);
win.x = point.x;
});
const win = new Window({
width:windowWidth,
height:list.height,
paddingH:20
}).loc(list).bot().mov(list.width);
win.add(new Pack());
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 300) the width of the window
height - (default 200) the height of window - including the titleBar if there is a titleBar
content - (default null) optional content to be centered in one of three formats:
a string or number to add a ZIM Label - default white
a ZIM DisplayObject such as a Circle or a Container with more objects, etc.
a content configuration object {} with the following properties - any are optional:
** see Panel() and Pane() for examples of content configuration object being used
header - a ZIM DisplayObject for the top of the content
message - text that will put into a ZIM Label - default color white - see color property
display - a ZIM DisplayObject for beneath the message
buttons - an array of ZIM Button objects or configuration objects {} as follows:
{label, color, rollColor, backgroundColor, rollBackgroundColor, call}
with call being a callback function for when the button is pressed
buttonScale - the scale for the buttons
color - the color of the message
spacingH - (default 20*buttonScale) horizontal space between the buttons
spacingV - (default 20) vertical space between the content areas
scrollBar - set to true if a default scrollBar is present or a number if custom
backgroundColor - (default dark) background color (use clear - or "rbga(0,0,0,0)" for no background)
borderColor - (default silver) border color
borderWidth - (default 1) the thickness of the border
padding - (default 0) places the content in from edges of border (see paddingH and paddingV)
padding is ignored if content x and y not 0 - and really only works on top left - so more like an indent
corner - (default 0) is the rounded corner of the window (does not accept corner array - scrollBars are too complicated)
swipe - (default auto/true) the direction for swiping set to none / false for no swiping
also can set swipe to just vertical or horizontal
scrollBarActive - (default true) shows scrollBar (set to false to not)
scrollBarDrag - (default false) set to true to be able to drag the scrollBar
scrollBarColor - (default borderColor) the color of the scrollBar
scrollBarAlpha - (default .3) the transparency of the scrollBar
scrollBarFade - (default true) fades scrollBar unless being used
scrollBarH - (default true) if scrolling in horizontal is needed then show scrollBar
scrollBarV - (default true) if scrolling in vertical is needed then show scrollBar
slide - (default true) Boolean to throw the content when drag/swipe released
slideFactor - (default .9) is the factor multiplied by dragging velocity (1 no slowing, .7 fast slowing)
slideSnap - (default true) slides past boundary and then snaps back to boundary when released - also VERTICAL, HORIZONTAL, and false
slideSnapDamp - (default .1) the damping to snap back to boundary
interactive - (default true) allows interaction with content in window
set to false and whole window will be swipeable but not interactive inside
shadowColor - (default rgba(0,0,0,.3)) the color of the shadow
shadowBlur - (default 20) set shadowBlur to -1 for no drop shadow
paddingH - (default padding) places content in from left and right (ignored if content x not 0)
paddingV - (default padding) places content in from top and bottom (ignored if content y not 0)
scrollWheel - (default true) scroll vertically with scrollWheel
damp - (default null) set to .1 for instance to damp the scrolling
titleBar - (default null - no titleBar) a String or ZIM Label title for the window that will be presented on a titleBar across the top
titleBarColor - (default black) the text color of the titleBar if a titleBar is requested
titleBarBackgroundColor - (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - (default fit label) the height of the titleBar if a titleBar is requested
draggable - (default true if titleBar) set to false to not allow dragging titleBar to drag window
boundary - (default null) set to ZIM Boundary() object - or CreateJS.rectangle()
onTop - (default true) set to false to not bring Window to top of container when dragging
close - (default false) - a close X for the top right corner that closes the window when pressed
closeColor - (default grey) - the color of the close X if close is requested
cancelCurrentDrag - (default false) - set to true to cancel window dragging when document window loses focus
this functionality seems to work except if ZIM is being used with Animate - so we have left it turned off by default
fullSize - (default false) - set to true to add a fullsize icon to the titleBar
to let user increase the size of the window to the frame - will turn into a reduce size icon
fullSizeColor - (default grey) - the color of the fullSize icon
resizeHandle - (default false) - set to true to rollover bottom right corner to resize window with resizeHandle
collapse - (default false) - set to true to add a collapse button to the titleBar that reduces the window so only the bar shows and adds a button to expand
also can double click bar to collapse window
collapseColor - (default grey) the color of the collapse icon
collapsed - (default false) set to true to start the window collapsed
optimize - (default true) set to false to not turn DisplayObjects visible false if they are not on within 300 pixels of the window
as the Window is scrolled, any objects within the content and any objects within one level of those objects
are set to visible false if their bounds are not hitting the the window bounds + 300 - thanks Ami Hanya for the suggestion
also see optimize property
resizeBoundary - (default null) add a ZIM Boundary() object for the resize handle - relative to the resize handle start position
new Boundary(-100, 0, 200, 0) - would allow the resize handle to move to the left or right 100 pixels but not up or down
new Boundary(0, -100, 0, 200) - would allow the resize handle to move to up or down 100 pixels but not left or right
new Boundary(0,0,100,100) - would allow the window to expand in x or y 100 pixels but not grow smaller
new Boundary(-100,-100,100,100) - would allow the window to shrink in x or y 100 pixels but not grow bigger
resizeVisible - (default false) set to true to always see the resizeHandle - if resizeHandle is set to true
continuous - (default false) set to true (or VERTICAL) to lock window to vertical access and ignore boundary
or set to HORIZONTAL to lock window to horizontal and ignore boundary
used internally for when scrolling should not be limited but rather wrapped such as with ZIM List with continuous:true
will set scrollBarActive to false
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(obj, index, center, replace) - supports DUO - parameters or single object with properties that match parameters
adds obj to content container of window (at padding) must have bounds set
you can add individual objects but may find it easier to make a Container with dimensions
then add and position objects in the container and add the container.
If adding individual objects and adjusting their x and y or scale, do so first and then add()
or if adjusting after adding and the object goes outside the window size then you should call update()
which will reset the scrollbars.
index is the level or layer in the content with 0 being at the bottom
center will center the content in the visible window
replace defaults to false and if set to true, removes all content then adds the obj.
returns window for chaining
remove(obj) - removes object from content container of window and updates - returns window for chaining
removeAll() - removes all objects from content container of window and updates - returns window for chaining
resize(width, height) - resizes the Window without scaling the content (also calls update() for scroll update)
width and height are optional - returns window for chaining
update() - resets window scrolling if perhaps the content gets bigger or smaller
update() does not quite update the dragBoundary due to a timeout in waiting for scrolls to be set
so if animating the position of a window, set the enable property to false before animating
then set the enable property to true on the animate call function
cancelCurrentDrag() - stop current drag on window - but add dragging back again for next drag
fullSize(state) - state defaults to true to set window to fullsize or set to false to go back to normal
must start with the fullSize parameter set to true
also see fullSized property
collapse(state) - state defaults to true to collapse or set to false to expand collapsed window
must start with the collapse parameter set to true
also see collapsed property
clone(recursive) - makes a copy with properties such as x, y, etc. also copied
recursive (default true) clones the window content as well (set to false to not clone content)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
backing - CreateJS Shape used for backing of Window
backgroundColor - the color of the backing
borderColor - the color of the border
borderWidth - the width of the border
contentContainer - ZIM Container used to hold added content (formerly the content property)
content - gives access to the content provided as a parameter to the Window()
** in the past, content refered to what is now the contentContainer
If a content config object {} was passed in the following properties are added to the Window()
header - reference to the header if provided
message - reference to the message if provided - this is a Label
text - reference to the text of the message if provided
display- reference to the display if provided
buttons - an array of the Button objects if provided
config - the original content config object {}
optimize - see optimize parameter - set to true (default) or false to optimize scrolling of Window
enabled - get or set whether the Window is enabled
scrollEnabled - get or set whether the Window can be scrolled
scrollBar - data object that holds the following properties (with defaults):
you can set after object is made - call window.update() to see change
scrollBar.horizontal = zim Shape // the horizontal scrollBar rectangle shape
scrollBar.vertical = zim Shape // the vertical scrollBar rectangle shape
scrollBar.color = borderColor; // the color of the scrollBar
scrollBar.size = 6; // the width if vertical or the height if horizontal
scrollBar.minSize = 12; // for the height if vertical or the width if horizontal
scrollBar.spacing = 3 + size + borderWidth / 2;
scrollBar.margin = 0; // adds extra space only at end by scrollBars
scrollBar.corner = scrollBar.size / 2;
scrollBar.showTime = .5; // s to fade in
scrollBar.fadeTime = 3; // s to fade out
scrollBar.speed = .5 // scrollwheel speed for x and y scrolling with mouse wheel
scrollX - gets and sets the content x position in the window (this will be negative)
scrollY - gets and sets the content y position in the window (this will be negative)
scrollXMax - gets the max we can scroll in x based on content width - window width (plus padding and margin)
scrollYMax - gets the max we can scroll in y based on content height - window height (plus padding and margin)
titleBar - access to the ZIM Container for the titleBar if there is a titleBar also has a backing property
titleBarLabel - access to the ZIM Label of the titleBar if there is a titleBar
closeIcon - access to the ZIM Shape if there is a close X
fullSizeIcon - access to the ZIM Container if there is a fullSize icon
fullSized - get or set whether the window is full sized - must start with fullSize parameter set to true
also see fullSize() method
collapseIcon - access to the ZIM Shape if there is a collapse triangle
collapsed - get or set whether the window is collapsed - must start with collapse parameter set to true
also see collapse() method
resizeHandle - access the ZIM Rectangle that makes up the resizeHandle when resizeHandle parameter is set to true
resizeHandle.removeFrom() would stop resize from being available and resizeHandle.addTo(window) would activate it again
continuous - get if window is set to continuous - see continuous parameter
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "select" event when clicked on in a traditional manner (fast click with little movement)
dispatches a "hoverover" event when rolled on without moving for 300 ms
dispatches a "hoverout" event when not hovering due to movement or mouseout on the window
dispatches a "scrolling" event when the window scrolls
dispatches a "close" event when the window is closed with the x on the titleBar if there is a titleBar
dispatches a "slidestart" event if slide is true and window starts sliding (on pressup)
dispatches a "slidestop" event if slide is true and window stops sliding
dispatches a "resize" event if resizing
dispatches a "collapse" event if collapsing
dispatches a "expand" event if expanding after being collapsed
dispatches a "fullsize" event if made fullscreen
dispatches a "originalsize" event if reduced from fullscreen
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Page
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
ZIM Page() is a Container() with Rectangle() backing.
For years, many questions were asked - how to make a page in ZIM.
Now, we have decided to officially answer that! ZIM Page().
An easy way to handle linear gradients is provided as well as a custom background
such as a ZIM Pizzazz pattern.
To keep things brief, Page is expected to fit the stage.
So border, corner, dashed, etc. has been left out.
If the page is smaller and these are desired...
old-school-it and make a Container and add the desired Rectangle.
SEE: https://zimjs.com/cat/page.html
SEE: Docs for ZIM Pages() as well to handle multiple pages.
SEE: ZIM Panel(), ZIM Pane() and ZIM Window() for alternatives.
NOTE A Page object will start with one child or two children if a pattern is specified.
NOTE Do not use Page with Layout as it will overlay the region backgroundColors - instead use a Container
NOTE as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const page = new Page(W, H, red, pink).addTo();
page.title = new Label("A Page!").loc(100,100,page);
page.content = new Circle().center(page);
page.nav = new Tabs().pos(0,100,CENTER,BOTTOM,page);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default zimDefaultFrame.width) the width of the Page
but backing is sized to screen.width if no width is provided
height - (default zimDefaultFrame.height) the height of the Page
but backing is sized to screen.height if no height is provided
color - |ZIM VEE| (default zim.light) the color of the page
color2 - |ZIM VEE| (default null) a second color which would form a zim.GradientColor() as the color
angle - (default 90) the angle for the gradient if there is a gradient
pattern - (default null) a DisplayObject that will be added to the page above the backing
For instance, import zim_pizzazz and use:
makePattern("slants", series(grey,dark), 20, 52, 40).alp(.2)
scalePattern - (default "fill") scale the pattern so it fills the window (formerly "bigger" or "outside")
set to false for no scaling or:
FIT or "fit" fits inside the Page keeping proportion (formerly "smallest")
FILL or "fill" fills the Page keeping proportion (formerly "biggest" or "outside")
FULL or "full" keeps both x and y scales - may stretch object (formerly "both")
cache - (default false or true for gradient or pattern) whether the backing and pattern is cached
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
clone(recursive) - makes a copy with properties such as x, y, etc. also copied
recursive (default false) - set to true to copy children of the object (these will not get custom properties, no drag, events, etc.)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
backing - access the backing Rectangle
pattern - access the pattern object if one is provided
color - get or set the color of the backing Rectangle
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Central
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
ZIM Central() is a Container() with its origin and registration point in the center.
It will resize to the stage so that it stays in the middle.
The container will scale only to fit within the stage height.
This is the same functionality as the classic three.js full window scaling.
Note, that the origin is in the middle of the stage - also like three.js
but the y values still are negative going up and positive going down like usual ZIM.
Objects would then be added to Central rather than the stage
to emulate this form of scaling.
This may work well with three.js on top of beneath ZIM using the Three helper module
There is a lay parameter that can be set to UNDER or OVER.
The interactive parameter can be set to true to control three.js or false to control ZIM.
Set the Frame scaling to FULL and add ZIM content to a Central to match the scaling of three.js.
See https://zimjs.com/three/central.html
NOTE as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// most likely in a FULL Frame scaling mode
const central = new zim.Central()
.addTo(); // or center() or centerReg() - will always just centerReg()
const circle = new Circle(100)
.center(central).alp(.5);
new Slider({max:1, value:.5})
.pos(0,200,CENTER,CENTER,central)
.wire(circle, "alpha");
PARAMETERS
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 1024) the width of the container - just use to adjust overall scale
height - (default 768) the height of the container - just use to adjust overall scale
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Layer
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Layer is a ZIM Container with transform controls.
ZIM transform() objects have their mousechildren turned off so they can be dragged and transformed.
This means there can be no interactivity inside the transformed object.
Layer provides a solution to nest transformed objects in transformable containers.
It does so by providing a titleBar that can be used to turn on and off the transform of the container
and allow its contents to be transformed when the transform controls of the Layer are turned off.
This is more than just hiding the transform tools but rather removing and adding them.
The Layer titleBar will always remain visible on the stage
If the Layer is moved (not by its titleBar) so that the titleBar hits the edge,
then the titleBar will become anchored to the edge (unless anchor is set to false)
This creates an independent titleBar that can be moved to any location.
The titleBarPos() method can also be used to separate the titleBar at any time.
Drop the titleBar on the top left corner of the Layer or doubleClick it to snap it back on to the layer
NOTE
Layers can be added to a Transform Manager and saved with the persist sytem.
NOTE
Layers can be added to Layers (nested) along with any other type of DisplayObject content.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
SEE: https://zimjs.com/explore/layer.htmlEXAMPLE
// adding the Layers above the content will allow pressing Layer titleBar objects inside other Layers
// adding everything right on the stage would not allow pressing titleBars inside other Layers - either way may be best, depending on content
const content = new Container(W, H).addTo();
const layers = new Container(W, H).addTo();
// create an outer layer with two inner layers - one holding a circle and the other two circles
const layer0 = new Layer(800, 500, "LAYER 0", layers).center(content);
const layer1 = new Layer(300, 400, "LAYER 1", layers).loc(50,50,layer0);
const circle1 = new Circle(50, pink).center(layer1).transform({visible:false});
const layer2 = new Layer(300, 400, "LAYER 2", layers).pos(50,50,true,false,layer0);
const circle2 = new Circle(50, green).center(layer2).mov(0, -80).transform({visible:false});
const circle3 = new Circle(50, blue).center(layer2).mov(0, 80).transform({visible:false});
// optionally store transforms
const t = new TransformManager([layer0, layer1, layer2, circle1, circle2, circle3], "layersID");
// t.clearPersist("layersID")
timeout(1, ()=>{
layer2.resetTitleBar();
layer2.turnOn();
// if moving manually, must call resize()
layer2.mov(30);
layer2.resize();
S.update();
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 500) the width of the Layer Container
height - (default 500) the height of the Layer Container not including the titleBar (which is not in the Container)
titleBar - (default "LAYER") a String or ZIM Label for the titleBar
titleBarContainer - (default null - zdf' stage) a container for the titleBar
can group these with other Layers and hide them all by hiding the container for instance
this also can help layer the titleBars above the content
backgroundColor - (default lighter) the background color of the titleBar
rollBackgroundColor - (default white) the roll background color of the titleBar
selectedBackgroundColor - (default granite) the selected background color of the titleBar
color - (default granite) the color of the titleBar text
rollColor - (default granite) the roll color of the titleBar text
selectedColor - (default moon) the selected color of the titleBar text
borderWidth - (default 1) the width of the ghost outline when the Layer is not selected
to adjust the transform controls border width use the transformObject parameter and set the borderWidth property
borderColor - (default borderColor) the color of the ghost outline when the Layer is not selected
to adjust the transform controls border color use the transformObject parameter and set the borderColor property
dashed - (default true) the dashed of the ghost outline when the Layer is not selected
to adjust the transform controls border dashed use the transformObject parameter and set the dashed property
transformObject - (default {borderColor:selectedBackgroundColor}) any of the transform parameters as an object literal
certain properties are overwritten by Layer as follows:
{events:true, visible:false, ghostColor:borderColor, ghostWidth:borderWidth, ghostDashed:dashed, ghostHidden:true}
use the transformControls.show() to show the transform controls once the Layer is made for instance:
timeout(.1, function(){layer.transformControls.show();}); // a timeout is needed as Layer gets created - sorry.
titleBarWidth - (default 100 + 30 if close) the width of the titleBar. 30 pixels will be added if close is true
titleBarHeight - (default 40) the height of the titleBar
titleBarX - (default null) the starting x position of the titleBar - see also titleBarPos() and resetTitleBar() methods
titleBarY - (default null) the starting y position of the titleBar - see also titleBarPos() and resetTitleBar() methods
titleBarDraggable - (default true) set to false to not let the titleBar be dragged.
this is useful with the titleBarPos() to create a stationary menu for the layers - for instance along the edge like tabs
close - (default true) - set to false to not use the close checkbox
WARNING: without the close checkbox, the user may make the layer bigger than the stage and not be able to deselect the layer
closeColor - (default selectedBackgroundColor) the border of the close checkBox
closeBackgroundColor - (default selectedBackgroundColor) the backgroundColor of the close checkBox
closeIndicatorColor - (default selectedColor) the indicator color of the close checkBox
anchor - (default true) set to false to not anchor the titleBar to the edge if dragged with the Layer (not the titleBar)
with anchor true, the user can dock the titleBar to the edges and then drag them to any desired location
the user can snap the titleBar back on the layer by dropping it on the top left corner of the layer or double clicking the titleBar
onTop - (default true) set to false to not bring the layer on top when selected
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
titleBarPos(x, y, right, bottom) - position the titleBar in the titleBarContainer - returns object for chaining
This will undock the titleBar from the Layer so it can be moved independently
unless titleBarDraggable is set to false
See also titleBarX and titleBarY parameters to start titleBars at a certain position
resetTitleBar() - dock the titleBar back on the Layer - returns object for chaining
toggle(state) - toggle the controls or turn on or off the controls by providing a Boolean state - returns object for chaining
resize(dispatch) - resize the Layer and its children if Layer is manually adjusted - returns object for chaining
for instance, layer.x = 10; layer.resize(); otherwise, the transform controls are broken!
normal layer transforming using the controls automatically resize.
Setting dispatch to true will dispatch a "transformed" event
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied (returns the new waiter for chaining)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
transformControls - the transform transformControls object - see below for a description
anchor - get or set whether the titleBar will anchor to the edges of the titleBarContainer
toggled - read only if Layer has its transform turned on - or use transformControls.visible
use toggle(state) to toggle controls or pass in true for show controls or false for hide controls
titleBar - access to the ZIM Container that holds the titleBar
titleBarDraggable - get or set whether the titleBar can be dragged
use with titleBarPos() to permanently positing the titleBar
checkBox - access to the ZIM CheckBox that shows when the Layer is active and close is true
button - access to the ZIM Button that makes up the titleBar
label - access to the ZIM Label that is on the Button for the titleBar
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the transformControls property described below for more options.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
TRANSFORM CONTROLS OBJECT
Layer receives a transformControls property
This may be slightly delayed as Layer is prepared on stage
var layer = new Layer().center();
timeout(100, function(){zog(layer.transformControls);}); // will probably do the trick
The transformControls property holds the following:
TRANSFORM CONTROL OBJECT PROPERTIES
visible - read only whether the controls are visible
ghost - read only as to whether the ghost outline is showing - set with showGhost and hideGhost
ghostEnabled - read only as to whether the ghost outline will be turned on and off - set with addGhost and removeGhost
scaleControls - reference to the Container that holds the corner boxes for scaling
stretchXControls - reference to the Container that holds the left and right boxes for stretching
stretchYControls - reference to the Container that holds the top and bottom boxes for stretching
rotateControls - reference to the Container that holds the outer circles for rotating
TRANSFORM CONTROL OBJECT METHODS
hide() - hides the controls - returns object for chaining
show() - shows the controls - returns object for chaining
recordData(toJSON) - returns an object with type, x, y, scaleX, scaleY, rotation, skewX, skewY, visible PROPERTIES
if toJSON (default false) is set to true, the return value is a JSON string
setData(data, fromJSON) - sets the properties to match the data object passed in - this should come from recordData()
if fromJSON (default false) is set to true, it will assume a JSON string is passed in as data
returns object for chaining
remove(noHide) - removes the controls - set noHide true if already hidden
add(noShow) - adds the controls back if then have been removed - set noShow true if not wanting to show
allowToggleOn() - sets the show / hide controls on with click
allowToggleOff() - removes the show / hide controls on with click
showGhost() - show the ghost outline - the ghostWidth or ghostColor must be set in initial parameters
hideGhost() - hide the ghost outline
toggleGhost(state) - if ghost is showing will hide ghost and if ghost is hidden will show ghost
or set state to true to show ghost or false to not show ghost
addGhost() - enable ghost outline functionality - the ghostWidth or ghostColor must be set in initial parameters
removeGhost() - disable ghost outline functionality
disable() - may show the controls if visible but cannot use them
enable() - turns the using of the controls back on
resize(dispatch) - call resize if the object is transformed in ways other than with the controls
set dispatch to true to dispatch a "transformed" event - if manually adjusted this will save to TransformManager
EVENTS
dispatches a "transformed" event when being transformed
the transformed event object has a transformType property
the transformType property has values of "size", "move", "rotate", "stretch", "reg", "reset"
the transformType also might be "resize" if resize(true) is called to dispatch a transformed event
the transformed event object also has a pressup property that is true if on pressup and null if from pressmove
dispatches "transformshow" and "transformhide" events for when click to hide or show controls
If TransformManager() is used there are more events available such as "persistset", etc.
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Waiter
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Adds a little animated three dot wait widget.
You need to call waiter.show() to show the waiter and waiter.hide() to hide it.
You do not need to add it to the stage - it adds itself centered.
You can change the x and y (with origin and registration point in middle).
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const waiter = new Waiter().show(); // show the waiter until assets load
F.loadAssets("cave02.jpg", "https://zimjs.org/assets/");
F.on("complete", ()=>{
waiter.hide();
new Pic("cave02.jpg").center();
S.update();
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
container - (default first frame's stage) the container that holds the waiter
speed - (default .6) cycle time in seconds (also see ZIM TIME constant)
foregroundColor - (default white) the dot color
backgroundColor - (default "orange") the background color
corner - (default 14) the corner radius of the waiter box
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (defaults rgba(0,0,0,.3)) set to -1 for no shadow
shadowBlur - (default 14) the blur of the shadow if shadow is set
fadeTime - (default 0) milliseconds to fade in and out
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show() - shows the waiter (returns the waiter for chaining)
hide() - hides the waiter
toggle(state - default null) - shows waiter if hidden and hides waiter if showing (returns the object for chaining)
or pass in true to show waiter or false to hide waiter
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied (returns the new waiter for chaining)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
display - reference to the waiter backing graphic
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
ProgressBar
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Adds a little progress bar that can be scaled if desired
Pass in to progress parameter of the Frame or LoadAssets call to operate
or use on its own with the show(), hide() methods and percent property
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const progressBar = new ProgressBar();
F.loadAssets({assets:"greeting.mp3", progress:progressBar});
// a bar will be centered on the default stage (or specify a container)
// the bar will show a percentage of asset bytes loaded
F.on("complete", ()=>{
// the bar will be removed when loading is complete
// must have interacted previously to play sound...
new Aud("greeting.mp3").play();
});
EXAMPLE
// testing progress bar:
new ProgressBar({barType:"rectangle"}).show().run(2); // run for 2 seconds
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
barType - (default "circle") set "rectangle" for rectangular progress bar
foregroundColor - (default green) the color of the bar
backgroundColor - (default dark) the color of the background
borderColor - (default backgroundColor) the color of the border - for "rectangle" barType
borderWidth - (default 10 "circle" or 0 "rectangle") the width of the border (or ring for "circle" barType)
padding - (default 2 for "circle" or 0 for "rectangle") the space between the bar and the backing
label - (null) set to a String or a ZIM Label to specifify label properties
color - (default foregroundColor) the color of the label if there is one
labelPosition - ("bottom" if label specified) also set to TOP to move label above progress bar
percentage - (default false) set to true to show percentage after label (set label to "" for only percentage)
corner - (default 15 for "rectangle" barType) set to 0 for square corners, etc.
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default rgba(0,0,0,.3)) set to -1 for no shadow
shadowBlur - (default 14) the blur of the shadow if shadow is set
backing - (default null) a Display object for the backing of the "rectangle" barType (eg. Shape, Bitmap, Container, Sprite)
See ZIM Pizzazz 3 - for patterns - these have a type of "Pattern" which makes them special
If a "pattern" is used then the normal backing will be used to mask the pattern
delay - (default .1) seconds to delay view of progress bar - helps not flash progress bar when content is cached (also see ZIM TIME constant)
fastClose - (default true) hide as soon as progress is done
The complete event is delayed slightly after the progress bar is loaded
Set to false to wait until the complete event triggers before removing the progress bar
container - (defaultFrame's stage) or specify a container to hold the progress bar
autoHide - (default true) set to false so bar does not hide when reaching 100%
width - (default 20/200 for circle/rectangle) set the width of the bar (for the circle the width is diameter)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show() - shows the progress bar (returns the progress bar for chaining)
hide() - hides the progress bar
toggle(state - default null) - shows progress bar if hidden and hides progress bar if showing (returns the object for chaining)
or pass in true to show progress bar or false to hide progress bar
run(time, close) - shows and runs the progress bar for the given time (default 3s) (also see ZIM TIME constant)
setting close to true or false will set the main class autoHide setting
thanks Racheli Golan for the request
setBacking(backing) - change the backing of the progress bar
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied (returns the new waiter for chaining)
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
percent - get or set the percent (0-100) complete of the progress bar
label - reference to the label if there is one
backing - reference to the backing shape. This may be the backing DisplayObject if provided
the backing will have a pattern property if a pattern is set for the backing
bar - reference to the bar shape
toggled - read-only Boolean that is true if progress bar is showing otherwise false
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
group - used when the object is made to add STYLE with the group selector (like a CSS class)
EVENTS
Dispatches a "complete" event when the loading or running is complete
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Indicator
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A row of dots or squares that can be used to indicate a step, page, level, score, etc.
The indicator can be used as an input as well but often these are small so may not be best to rely on.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const lights = new Indicator({fill:true});
lights.index = 0; // set the first light on
lights.center();
S.on("stagemousedown", ()=>{
// increase the indicator lights each click (then start over)
lights.index = (lights.index+1) % lights.num;
});
S.update();
EXAMPLE
// lightening indicator!
new Indicator({
indicatorType:new Emoji("\u26a1\ufe0f"),
fill:true,
interactive:true
}).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 100) width of indicator
height - (default 50) height of indicator
num - (default 6) the number of lights
foregroundColor - (default "orange") color of the light(s) turned on
backgroundColor - (default grey) color of the light(s) turned off
borderColor - (default -1 for no border) border color of lights and backdrop (if backdrop)
borderWidth - (default 1 if stroke is set) the size of the stroke in pixels
backdropColor - (default -1 for no backdrop) backdrop rectangle around lights
corner - (default 0) the corner radius if there is a backdropColor provided
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
indicatorType - (default "dot" or "circle") can also be "box" or "square", "heart", "star"
or pass in a ZIM Emoji and Indicator will fade alpha to backgroundAlpha parameter setting for unselected emojis
or pass any DisplayObject and the this will be used
selectedIndicatorType - (default indicatorType) - see indicatorType parameter for options
this will be shown for all the selected indicators
fill - (default false) set to true to fill in lights (or show selected indicators) to the left of the index
scale - (default 1) for all the lights including spacing
lightScale - (default 1) scale for each light - keeping the spacing unchanged
interactive - (default false) set to true to make lights clickable
clicking on first light when first light is only light on, will toggle light
shadowColor - (default rgba(0,0,0,.3)) set to -1 for no shadow
shadowBlur - (default 5) the shadow blur if shadow is set
index - (default 0) - set the index at start. Use -1 for no indicator at start.
backgroundAlpha - (default 1 or .2 if indicatorType is Emoji) - affects only Emoji and custom DisplayObject indicatorType
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets or sets the current index of the indicator
num - the assigned num value (how many light objects) (read only)
backdrop - gives access to the backdrop if there is one Rectangle
lights - an array of the light objects (zim Circle or Rectangle objects)
lightsContainer - gives access to the lights createjs.Container with its Circle or Rectangle children
enabled - set to false to disable component
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event if press is true and indicator is pressed on and lights change
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
TextInput
zim class - extends a zim.Window which extends a zim.Container which extends a createjs.Container
DESCRIPTION
Makes an input text field like an HTML form input type text field.
This will be right on the canvas so can be layered with canvas objects
as opposed to the ZIM TextArea() which is an HTML tag overlay.
Thanks Cajoek for coding the text for the class.
WARNING: currently a single line is available (so height is not at this point useful)
See: https://zimjs.com/explore/textinput.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const input = new TextInput().loc(100,100); // adds a default input field to the stage
new Button({label:"SUBMIT"}).loc(100, 200).tap(()=>{
zog(input.text); // whatever is typed into the LabelInput
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
width - |ZIM VEE| (default 300) - the width of the backgroundColor of the field - set to -1 for expanding width
This will limit the length of the text added to the field
In the future, scrolling text may be provided
height - |ZIM VEE| (default size plus paddingV) - the height of the backgroundColor for the label
Currently, the text is always one line.
In the future, multi-line functionality may be provided
Until then, use a ZIM TextArea for multiline.
placeholder - |ZIM VEE| String to show when no text is entered - will disappear when there is text entered
text - |ZIM VEE| String for the the text of the label
size - (default 36) the size of the font in pixels
font - (default arial) the font or list of fonts for the text
color - |ZIM VEE| (default dark) color of font
backgroundColor - |ZIM VEE| (default lighter) background color - set to -1 for no background
borderColor - |ZIM VEE| (default null) the background stroke color
borderWidth - (default null) thickness of the background border
maxLength - (default null) set to limit the number of characters in the field
password - (default false) set to true to show **** for text to hide password
this will be replaced by inputType in upcoming versions of ZIM
selectionColor - (default color) the selection color of the text
selectionAlpha - (default .2) the alpha of the selection color
cursorColor - (default color) the blinking cursor in the text
cursorSpeed - (default .5) seconds for which the cursor blinks
shadowColor - (default -1) for no shadow - set to any css color to see
shadowBlur - (default 14) if shadow is present
align - ((default LEFT) text registration point alignment
also RIGHT for right aligned
also CENTER - (experimental) this adds a maxWidth to keep text centered
the maxWidth that is added can be overwritten
corner - (default 0) the round of corner of the background if there is one
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
padding - (default 5 if backgroundColor set) places the border this amount from text (see paddingH and paddingV)
padding parameters are ignored if there is no backgroundColor set
paddingH - (default padding) places border out at top bottom
paddingV - (default padding) places border out at left and right
shiftH - (default 0) move the label (CreateJS Text) inside the Label container horizontally
shiftV - (default 0) move the label (CreateJS Text) inside the Label container vertically
rollPersist - (default false) set to true to maintain rollover stage as long as mousedown or press is activated (used by Buttons)
scrollBarActive - (default false) set to true to show scrollBar
scrollBarDrag - (default false) set to true to be able to drag the scrollBar
scrollBarColor - (default borderColor) the color of the scrollBar
scrollBarAlpha - (default .3) the transparency of the scrollBar
scrollBarFade - (default true) fades scrollBar unless being used
scrollBarH - (default true) if scrolling in horizontal is needed then show scrollBar
scrollBarV - (default true) if scrolling in vertical is needed then show scrollBar
readOnly - (default false) set to true for field to be readOnly - also see readOnly property
inputType - (default "text") set to "text", "number", "password", "email"
number has 0-9 . + - / * % $ available
this will replace the password parameter in upcoming versions of ZIM
rtl - (default ZIM DIR) the direction of the text. Also set "rtl" in the HTML tag dir parameter for RTL
uppercase - (default false) set to true to force uppercase letters
placeholderInstant - (default true) set to false to not remove the placeholder as soon as the cursor is in the field
keyboardShift - (default false) set to true to lift stage at least 1/4 height or up to label y/2 to raise input above keyboard
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
resize(width, height) - resizes the field dimensions (inherited from Window) returns object for chaining
clone(exact) - makes a copy with properties such as x, y, etc. also copied
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if the object's color is [blue, green]
then its clone might be blue or green - which could be different than the original
If exact is set to true then the clone will be the color of the original object
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
all methods of ZIM Window()
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
text - references the text property of the CreateJS Text object
label - references the ZIM Label object of the TextInput
this is actually a LabelInput that extends a ZIM Label
see the STATIC PROPERTY LabelInput entry below
placeholderLabel - refrerence to the placeholder label
htmlTag - access to the hidden HTML input tag
focus - get or set the focus of the TextInput
selection - access to selection ZIM Rectangle
use this to set color or blendMode of selection
selectionAlpha - get or set the alpha of the selection
blinker - access to the blinking cursor ZIM Rectangle
use this to set color or blendMode of blinker
size - the font size of the Label (without px)
use textInput.resize() if there are selection problems after setting size
often a resize() is desired anyway so manually calling avoids double resizing
font - get or set the font of the text
align - get or set the horizontal alignment of the text
values are LEFT and RIGHT and CENTER (experimental)
color - gets or sets the label text color
backgroundColor - gets or sets the background color
readOnly - get or set the field as readOnly - also see readOnly parameter
enabled - default is true - set to false to disable
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
all properties of ZIM Window()
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
STATIC PROPERTY
LabelInput() - a static class so use new TextInput.LabelInput() to create.
This class is an editable label that expands in size as it is typed into
The TextInput is a ZIM Window with a LabelInput inside
The LabelInput has all the parameters of a ZIM Label with the following added after the size parameter:
maxLength - (default null) the maximum number of characaters the text can have
password - (default false) turn text into password text * symbols
selectionColor - (default - the text color) the color of the selection
selectionAlpha - (default .2) the alpha of the selection
blinkerColor - (default - the text color) the color of the blinker cursor
blinkerSpeed - (default .5) the speed of the blinker cursor
Some parameters of LabelInput such as rollColor and rollPersist are ignored - but kept in the signature to match Label for ease
an inputType parameter is available before the style parameter with a value of "text", "number", "email", "password"
as well an uppercase parameter is available just before the style parameter
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
EVENTS
focus, blur are dispatched when the text gains and loses focus
input is dispatched when the input text is typed or pasted into
capture the key with the event object data property
change is dispatched when the input text is different after losing focus (except if text is set programmatically)
capture the key with the event object key or keyCode properties
See the events for HTML input field of type text
See the events for ZIM Window()
See the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
List
zim class - extends a zim.Window which extends a zim.Container which extends a createjs.Container
DESCRIPTION
A vertical or horizontal list of items.
This is really a zim.Tabs object inside a zim.Window object.
The list can be strings, numbers or Label objects and these are added to Tabs buttons.
The list can also include any DisplayObject with bounds (which most ZIM objects have except a Shape needs bounds set manually with setBounds()).
If the object is not a string, number or Label then selection will not highlight and currently animateTo() may not work if size is different.
See: https://zimjs.com/explore/list.html
See: https://zimjs.com/explore/listObjects.html
ACCORDION
An accordion is a list with nested sections that expand open.
A special accordion object can be passed to the list parameter
that includes the menu items, styles for the sub menus
and properties to animate, shade and indent the sub menus.
See: https://zimjs.com/ten/accordion.html
CONTINUOUS
As of ZIM 015 a List can be made continuous
So it will continually wrap. The scrollbars will be removed for this.
See: https://zimjs.com/015/continuous.html
PULLDOWN AND LIST COMPONENTS
The pulldown parameter can be set to true to make list act like a pulldown
This hides the backdrop and border and can be set to be collapsed or expanded
There are component items available for slider, checkbox and colorPicker
See: https://zimjs.com/ten/pulldown.html
There is also a checkBox parameter to make a list of checkboxes
This acts like a multiple select list
See: https://zimjs.com/ten/listcheckbox.html
SPACING, PADDING, INDENTING
These adjust depending on vertical or horizontal settings
The spacing is the distance between items (default 2)
The padding is the distance around the items but not between (default spacing)
So changing the spacing can seem to change the padding - but that can be overridden
There is also paddingV and paddingH that can be adjusted (default padding)
Indent only works with custom items in the list in left, right alignment or top, bottom valignment
This moves the items away from their alignment
There is also label indenting for items with labels - and labelIndentV and labelIndentH
NOTE
List can have a ZIM Organizer added with the organizer parameter
The organizer lets the user add, remove and move items up, down, to the top or the bottom
See: https://zimjs.com/docs.html?item=organizer
See: https://zimjs.com/explore/organizer.htmlNOTE
set the enable property to false as animating the position of the List object (or its parent Window)
then set the enable property to true on the animate call function. See update() in Window docs for more
NOTE
to add ZIM Swipe() to objects in List set the overrideNoSwipe parameter of Swipe to true
NOTE
if animating the List off screen then either turn optimize:false
or use list.update() in the "animation" event with the animate({events:true})
for a List in Pages use:
pages.on("pagetransitioned", ()=>{
list.update();
});
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const list = new List({
list:["Enormous", "Big", "Medium", "Small", "Puny"],
viewNum:3, // this number will change the size of the list elements (default is 5)
}).center()
S.update();
EXAMPLE
// make a pulldown - this must start with a name for the list
// see https://zimjs.com/ten/pulldown.html for nested lists
const data = {
"MONSTERS":["Ghost", "Ghoul", "Vampire", "Werewolf", "Skeleton"]
}
const list = new List({
list:{menu:data, bloom:true, whither:true},
pulldown:true,
pulldownToggle:true // if want list to close when selected or stage is selected
}).center();
S.update();
EXAMPLE
// make a list with a width of 300 be resizeable
// from 100 width to 500 width
new List({
width:500,
align:LEFT,
resizeHandle:true,
resizeBoundary:new Boundary(0,0,-400,0)
}).resize(300).center()
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 300) width of list
height - (default 200) height of list
list - (default Options 1-30) an array of strings, numbers or zim Label objects - these will be added to zim Tabs Buttons
or include any DisplayObject with bounds - these will not get highlighted but will indicate a change event and index
currently objects with different sizes may not animateTo() properly - this will be fixed soon.
A special Accordion object literal {} can be provided - see: https://zimjs.com/ten/accordion.html
with the following properties:
menu - a SIMPLE or COMPLEX hierarchy input - see ZIM Hierarchy() in the Code module
note: if just providing the menu and the rest of the properties below are default
then the Accordion object literal can be the SIMPLE or COMPLEX hierarchy input.
In other words, no need to pass in {menu:{blah}} just pass in {blah}
open - (default false) set to true to start the list opened
shade - (default .2) the alpha of indented shade in sub menus - or false for no shading
shift - (default 15) the pixels to indent the shade - and left or right aligned text of sub menus - or false for no indenting
dim - (default .1) the alpha of dark background overlay on sub menus - or false for no dimming
bloom - (default false) time in seconds for each submenu item to be added - or false to not animate sub menus in - if true default time is .1 second
whither - (default false) time in seconds for each submenu item to be removed - or false to not animate sub menus out - if true default time is .1 second
expander - (default "plus") set to "arrow" or "none" to change the expander icon - thanks Christopher Browne and Ofweird Top for the suggestions
subStyles - (default null) an array of style objects for each sublevel - with all the color and background color properties
See: https://zimjs.com/ten/accordion.html
note: the Accordion List is currently incompatible with the Organizer, addTo() and removeFrom()
viewNum - (default 5) how many items to show in the width and height provided
adjusting this number will also change the overall scale of custom items for horizontal lists
(this does not affect vertical lists due to the way vertical tabs are optimized)
or see the noScale parameter to avoid scaling custom items in horizontal lists
if no items are provided to start but rather added with addAt() then choose a viewNum that roughly matches how many items will fit in the view
vertical - (default true) set to false to make a horizontal list
currentSelected - (default false) set to true to show the current selection as highlighted
align - (default CENTER) horizontal align
set to START to align LEFT for ZIM DIR constant is "ltr" or RIGHT when DIR="rtl" - END is the opposite
valign - (default CENTER) vertical align
labelAlign - (default CENTER) horizontal align of the label only
labelValign - (default CENTER) vertical align of the label only
labelIndent - (default indent) indent of label when align or valign is set - usually same as indent unless custom objects are in list
labelIndentH - (default indent) horizontal indent of label when align or valign is set
labelIndentV - (default indent) vertical indent of label when align or valign is set
indent - (default 10) indent of items when align or valign is set and there are custom objects in list
spacing - (default 2) is the pixels between tab buttons
backgroundColor - (default tin) the background color of the list elements (unless custom object)
rollBackgroundColor - (default grey) the background color of the list element as rolled over
selectedBackgroundColor - (default charcoal) the background color of the list element when selected
backdropColor - (default dark) the background color of the list window (any CSS color)
color - (default white) the text color of a deselected list element when not rolled over
rollColor - (default color) the rollover color
selectedColor - (default color) the text color of the selected list element
selectedRollColor - (default color) the text color of the rolled over selected list element
borderColor - (default silver) border color
borderWidth - (default 1) the thickness of the border
padding - (default 0) places the content in from edges of border (see paddingH and paddingV)
corner - (default 0) is the rounded corner of the list (does not accept corner array - scrollBars are too complicated)
swipe - (default auto/true) the direction for swiping set to none / false for no swiping
also can set swipe to just vertical or horizontal
scrollBarActive - (default true) shows scrollBar (set to false to not)
scrollBarDrag - (default true) set to false to not be able to drag the scrollBar
scrollBarColor - (default borderColor) the color of the scrollBar
scrollBarAlpha - (default .3) the transparency of the scrollBar
scrollBarFade - (default true) fades scrollBar unless being used
scrollBarH - (default true) if scrolling in horizontal is needed then show scrollBar
scrollBarV - (default true) if scrolling in vertical is needed then show scrollBar
scrollBarOverlay - (default true) set to false to not overlay the scrollBar on the content
overlaying could hide content - but without overlay, content less than window size will show gap when no scrollBar
slide - (default true) Boolean to throw the content when drag/swipe released
slideFactor - (default .95) is the factor multiplied by dragging velocity (1 no slowing, .7 fast slowing)
slideSnap - (default true) slides past boundary and then snaps back to boundary when released - also VERTICAL, HORIZONTAL, and false
slideSnapDamp - (default .1) the damping to snap back to boundary
shadowColor - (default rgba(0,0,0,.3)) the color of the shadow
shadowBlur - (default 20) set shadowBlur to -1 for no drop shadow
paddingH - (default padding) places content in from left and right
paddingV - (default padding) places content in from top and bottom
scrollWheel - (default true) scroll vertically with scrollWheel
damp - (default null) set to .1 for instance to damp the scrolling
titleBar - (default null - no titleBar) a String or ZIM Label title for the list that will be presented on a titleBar across the top
titleBarColor - (default black) the text color of the titleBar if a titleBar is requested
titleBarBackgroundColor - (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - (default fit label) the height of the titleBar if a titleBar is requested
draggable - (default true if titleBar) set to false to not allow dragging titleBar to drag list
boundary - (default null) set to ZIM Boundary() object - or CreateJS.rectangle()
onTop - (default true) set to false to not bring list to top of container when dragging
close - (default false) - a close X for the top right corner that closes the list when pressed
closeColor - (default grey) - the color of the close X if close is requested
collapse - (default false) - set to true to add a collapse button to the titleBar that reduces the list so only the bar shows and adds a button to expand
collapseColor - (default grey) - the color of the collapse icon
collapsed - (default false) set to true to start the list collapsed
excludeCustomTap - (default false) set to true to exclude custom buttons from tap() which would override existing tap() on the custom buttons
organizer - (default null) the ZIM Organizer for the list
checkBox - (default false) set to true to turn labeled list into a list of ZIM CheckBox objects - thanks Dale789 for the prompting!
See: https://zimjs.com/ten/listcheckbox.html
use selected.checkBox to get access to the selected CheckBox
use the checkBoxes property to get a list of the CheckBox objects
use setCheck(index, type), setChecks(type), getCheck(index) methods to manipulate
use STYLE to set CheckBox size
pulldown - (default false) set to true to have List act like a Pulldown
use tapClose and offClose parameters to optionally adjust behaviour
See: https://zimjs.com/ten/pulldown.html
clone - (default false) set to true to add clones of the list items rather than the items themselves
cancelCurrentDrag - (default false) - set to true to cancel window dragging when document window loses focus
this functionality seems to work except if ZIM is being used with Animate - so we have left it turned off by default
index - (default 0) - set the index at start - set to -1 for no selection
noScale - (default false) - set to true to not scale custom items - this ignores viewNum
pulldownToggle - (default false) - set to true to collapse list in pulldown mode when final item is selected or pressing off list
optimize - (default true) set to false to not turn DisplayObjects that are not on the stage visible false
as the Window is scrolled, any objects within the content and any objects within one level of those objects
are set to visible false if their bounds are not hitting the stage bounds
resizeHandle - (default false) - set to true to rollover bottom right corner to resize list with resizeHandle
currently, the List content does not automatically expand
so create the list with a width as wide as it will go
then call the resize() method to start the list at the desired width
resizeBoundary - (default null) add a ZIM Boundary() object for the resize handle - relative to the resize handle start position
new Boundary(-100, 0, 200, 0) - would allow the resize handle to move to the left or right 100 pixels but not up or down
new Boundary(0, -100, 0, 200) - would allow the resize handle to move to up or down 100 pixels but not left or right
new Boundary(0,0,100,100) - would allow the list to expand in x or y 100 pixels but not grow smaller
new Boundary(-100,-100,100,100) - would allow the list to shrink in x or y 100 pixels but not grow bigger
resizeVisible - (default false) set to true to always see the resizeHandle - if resizeHandle is set to true
continuous - (default false) set to true to make the list scroll continuously - should have more elements than the viewNum for this
closeOthers - (default false) set to true to close any open branches before expanding selected branch
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
animateTo(index, timePerItem) - animate list to index at given time per item (default 50ms) - returns object for chaining
addAt(items, index, style, clone) - an array of items to insert at an index in the list - returns object for chaining
if the list is made with no items to start and items are added with addAt() then set the List() viewNum parameter value to match roughly how many items will fit in view
clone defaults to false - set to true to add a clone of the item or items to the list
note: does not support continuous at this time (whereas removeAt() does support continuous)
removeAt(number, index) - remove a number of elements (default 1) from the list starting at and including the index - returns object for chaining
note: does support continuous (whereas addAt() does not support continuous)
clear() - clears the list
first() - select first list element - returns object to chain
last() - select last list element - returns object to chain
toggle(state, index) - for an accordion, will close the accordion if open or open if closed
passing in true will open (or keep opened), passing in false will close (or keep closed)
pass in an index to open an accordion to that index (indexes always start at 0)
the way the index works is that it is based on visible items
pass in an array to the index parameter to open inner accordions
remember, the index is based on all visible items and does not restart at 0 for nested items
there is a 50ms delay after each index is chosen as the accordion opens up
example:
4 items showing and index 1 (second item) has 5 things, the second of which has 3 things.
toggle(true, [1, 3, 4])
would open outer index 1 showing five more
the 3 index is now the 1 index of the five
so 3 would open the 1 index of those 5 showing 3 more
the 4 index is now the 0 index of those three
so 4 would open the 0 index of those three
also see toggled property (which only works on the root) and openAtNum()
note - in pulldown mode cannot call toggle() from change or tap methods - see pulldownToggle parameter instead
setCheck(index, type) - set the CheckBox at an index to true or false (the type parameter)
setChecks(type) - set all CheckBoxes to true or false (the type parameter) returns object for chaining
getCheck(index) - get the checked value of the CheckBox at an index
cancelCurrentDrag() - stop current drag on list - but add dragging back again for next drag
collapse(state) - state defaults to true to collapse or set to false to expand collapsed list
must start with the collapse parameter set to true
also see collapsed property
openAtLevel(level) - open a level of an accordion list
level 0 shows first level, 1 shows second level, etc.
openAtNum(idNum, closeOthers) - open an accordion list at a specific id number
view the tree property in the console (F12) and expand the data property to see ids
and then expand any ids to see more ids nested inside
the idNum should be something like 6 or 12 without the word id.
closeOthers defaults to false - set to true to close any open branches before opening at idNum
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
COMPONENT LIST ITEMS
These static methods make special List items with components
See: https://zimjs.com/ten/pulldown.html
Each may have a label, min, max, starting val, steps, etc.
Each has a call parameter for the function to call when the component changes
There are alternatively obj and property parameters
Setting these will change the property of the obj to the value of the component
Each will be given a call property of the call function
This can be changed dynamically if desired.
List.slider(label, min, max, val, call, step, decimals, obj, property, paddingLeft, paddingRight, factor, offset, backgroundColor)
A static method (use it like List.slider("fps", 0, 60, 20, doFps)) to make a slider List item
decimals defaults to 0 so if using decimals set to 1, 2, 3, etc. to adjust the decimals on the stepper (at right)
factor will multiply the slider value only in the stepper
offset will start the stepper offset by that amount
this lets the stepper value be factored and offset from the actual slider value
List.checkBox(label, checked, call, obj, property, paddingLeft, paddingRight, backgroundColor)
A static method (use it like List.checkBox("visible", checked, doVisible)) to make a checkBox List item
List.colorPicker(label, color, picker, call, obj, property, paddingLeft, paddingRight, backgroundColor)
A static method (use it like List.colorPicker("color", red, docColor)) to make a colorPicker List item
picker is an optional custom ZIM ColorPicker
This static method is used internally by the checkBox parameter of List
It can be used to create a checkBox list element - but also see List.checkBox() above
which is a little different and matches the format of the other List Items
List.checkItem(text, width, paddingH, paddingV, color, rollColor, backgroundColor, rollBackgroundColor, selectedColor, selectedRollColor, selectedBackgroundColor, selectedRollBackgroundColor)
A static method (use it like List.checkItem("hello", 30, 300, 10, 10, white, etc.))
To add a checkItem to a plain list use:
new List({list:["goodbye", List.checkItem("hello", 30, 300, 10, 10, white), "what?"]})
ALSO
All Window methods such as resize()
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - get or set the index of the selected list element
indexPlusPosition set the index and scroll the index into view - might be broken for lists with custom objects of different heights
accordionIndex - read only index of the selected item inside an accordion otherwise is undefined
selected - gets the current selected list object (ie. a Button)
use selected.checkBox to access the selected CheckBox if checkBox parameter is true
if custom objects are in the list then use selected.content to access the custom object\
value - gets or sets the current value - in setting, it matches the first label that has the value anywhere in it
currentValue - same as value - kept in for backwards compatibility
text - gets or sets the current selected label text
label - gets current selected label object
items (or list) - read-only array of list button objects or objects in the list
this will change from the list entered as parameters as strings are turned into tab buttons, etc.
use addAt() and removeAt() methods to manipulate
custom items can be accessed using item.content - as the item is a container with a backing then content
each item has the following properties:
index, label, expander (Label for accordion +- or arrows), listZID (see Hierarchy) and other properties depending on the item
checkBoxes - read-only array of CheckBox objects if checkBox parameter is true
itemsText - read-only array of text for labels (or null element if no label)
itemWidth - the width of each item (unless custom items)
itemHeight - the height of each item (unless custom items)
length - read-only length of the list
tabs - a reference to the tabs object used in the list
organizer - a reference to the organizer object if used
originalList - if an accordion object is provided this is the reference to that object
tree - if an accordion object is provided this is the active tree data
this will also give ids that can be used with the openAtNum(idNum) method
vertical - read-only true if list is vertical or false if horizontal
toggled - for accordion get or set whether the main (root) accordion is open (true) or closed (false)
also see toggle() chainable method for more options
note - in pulldown mode cannot call toggled from change or tap methods - see pulldownToggle parameter instead
collapseIcon - access to the ZIM Shape if there is a collapse triangle
collapsed - get or set whether the list is collapsed - must start with collapse parameter set to true
also see collapse() method
enabled - default is true - set to false to disable
ALSO
see all Window properties - like titleBar, titleBarLabel, resizeHandle, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event - then use index or text to find data
dispatches a "bloom" event for each item that is created when blooming
this receives an event object with an item property for the list item that was just opened
dispatches an "expanded" event when items have been expanded
this receives an event object with an items property of the items just opened
dispatches a "collapsed" event when items have been collapsed
ALSO
All Window events including "scrolling"
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Stepper
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Lets you step through a list of numbers or strings with arrows and keyboard arrows.
Uses mousedown to activate and defaults to stepping while pressing down
and going faster if you drag away from your press.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const stepper = new Stepper().center().change(()=>{
zog(stepper.index);
zog(stepper.value);
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
list - (default 0-10) pass in an array of strings or numbers to display one at a time
passing in an array will change the stepperType parameter from "number" to "list"
for instance a set of words ["hello", "goodbye", "wow", "omg!"]
would need a stepperType of "list" to be set and a larger width
width - (default 100) is the width of the text box (you can scale the whole stepper if needed)
backgroundColor - (default white) for the arrows and the text box
borderColor - (default null) stroke color for the box
borderWidth - (default 1 if borderColor) stroke thickness for the box
label - (default null) which can be used to define custom text properties
vertical - (default false) set to true if you want the arrows above and below the text
arrows - (default true) - use graphical arrows (also see keyArrows to turn off keyboard arrows)
corner - (default 10) is the radius of the text box corners - set to 0 for square corners
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default rgba(0,0,0,.3)) set to -1 for no drop shadow
shadowBlur - (default 14) value for shadow blur if shadow is set
continuous - (default false) set to true to loop around or go back past 0 index
display - (default true) set to false just to just show the arrows and not the value
press - (default true) will advance on label mousedown - set to false to not advance on mousedown
hold - (default true) set to false to not step with extended press down
holdDelay - (default .4) time (seconds) to wait for first step with hold (also see ZIM TIME constant)
holdSpeed - (default .2) time (seconds) between steps as holding (also see ZIM TIME constant)
draggable - (default true) set to false to not step when dragging
dragSensitivity - (default .1) .01 changes really quickly - 1 changes at base rate
dragRange - (default 200) absolute distance (pixels) from press the drag will reach maximum
stepperType - (default "number" unless passing in an array to list) makes numbers, words, letters to step through
also stepperType "list", "letter" - these get ranges below
min - (default 0 for number and "A" for letter) the minimum value (can make min bigger than max) (not for list stepperType)
max - (default 10 for number and "Z" for letter) the maximum value (can make max smaller than min) (not for list stepperType)
step - (default 1) the step value each time - can be decimal (only positive, only for number stepperType)
step2 - (default set to step) the step value when dragging perpendicular to main horizontal or vertical direction
step2 will run with draggable set to true or with arrows2 set below (only positive, only for number stepperType)
arrows2 - (default true if step2 different than step and stepperType number - else false) secondary arrows perpendicular to main horizontal or vertical direction
arrows2 will activate step2 above (only for number stepperType)
arrows2Scale - (default .5) the scale relative to the main arrows
keyEnabled - (default true) set to false to disable keyboard search / number picker
keyArrows - (default true) set to false to disable keyboard arrows
rightForward - (default true) set to false to make left the forward direction in your list
downForward - (default true except if stepperType is "number" then default false) set to false to make up the forward direction in your list
index - (default 0) set the index at start
value - (default null) set the value at start
arrowColor - (default backgroundColor) set the arrow color
arrowScale - (default 1) set the arrow scale
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
currentValue - same as value - kept in for backwards compatibility
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
next() - goes to next
prev() - goes to previous
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets or sets the current index of the array and display
value - gets or sets the current value of the array and display
currentValue - same as value - kept in for backwards compatibility
valueEvent - gets or sets the current value and dispatches a "change" event if set and changed
stepperArray - gets or sets the list
containerPrev, containerNext - access to the zim Container that holds the arrows
arrowPrev, arrowNext - access to the zim Triangle objects
arrowPrev2, arrowNext2 - access to the zim Triangle objects for arrows2
min, max - only for number mode at the moment - currently, do not change the max to be less than the min
label - access to the Label
textBox - access to the text box backing shape
continuous - does the stepper loop
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
EVENTS
dispatches a "change" event when changed by pressing an arrow or a keyboard arrow
(but not when setting index or value properties)
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Slider
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A traditional slider - will give values back based on min and max and position of button (knob).
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const slider = new Slider({step:1})
.center()
.change(() => {
zog(slider.value); // 0-10 in steps of 1
});
// or create an on("change", function) event (do not chain on)
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
min - |ZIM VEE| (default 0) the minimum value for the slider
max - |ZIM VEE| (default 10) the maximum value for the slider
step - |ZIM VEE| (default 0) 0 is continuous decimal - 1 would provide steps of 1, 2 would provide steps of 2, etc.
button - (default small button with no label) - a zim Button or string as follows:
"pill" - a narrow rectangle with rounded corners
"aztec" - a quadrilateral with fat side and skinny side (default for sound)
"circle" - a circle - can be oval with different width or height
"grip" - adds three grip lines to button
barLength - (default 300) the length of the bar (the slider slides along its length)
barWidth - (default 3) the width of the bar (how fat the bar is)
barColor - (default granite) the color of the bar (any CSS color)
vertical - (default false) set to true to make slider vertical
useTicks - (default false) set to true to show small ticks for each step (step > 0)
tickColor - (default barColor) set the tick color if ticks are set
tickStep - (default step - or 1 if no step and useTicks is true) set to adjust tick amount
if using semiTicks, this is the step between the semiTicks
a tickStep of .1 and semiTicks of 4 would lead to main ticks of 0, .5, 1, 1.5, 2, 2.5, etc.
with five spaces between main ticks
semiTicks - (default 4) add a number of semiTicks. 1 would add one smaller tick between ticks, 4 would add 4 smaller ticks, etc.
tickScale - (default 1) scale the height of the ticks
semiTickScale - (default 1) scale the height of the semiTicks
accentSize - (defualt 0) height of a bar next to slider that can be used to accent selection
accentOffset - (default 24) distance from edge of slider the accent will show
accentColor - (default zim.pink) color of filled part of accent
accentBackgroundColor - (default clear) color of background of accent
accentDifference - (default -.25) pixels accent background is bigger (or smaller if negative) than accentSize
this is used to stop bleeding of accent background
but can also be used to make the accent half the width of the background so it runs in a track, etc.
or fatter than the background so it runs on a wire or mono-rail
sound - (default false) - set to true to adjust various defaults for ticks, accent, button
inside - (default false) set to true to fit button inside bar (need to manually adjust widths)
keyArrows - (default true) set to false to disable keyboard arrows
keyArrowsStep - (default 1% of max-min) number to increase or decrease value when arrow is used
if step is set, then this value is ignored and set to step
keyArrowsH - (default true) use left and right arrows when keyArrows is true
keyArrowsV - (default true) use up and down arrows when keyArrows is true
damp - (default null) set to value such as .1 to damp the slider value
use with Ticker rather than "change" event - eg:
Ticker.add(()=>{circle.x = slider.value;});
value - |ZIM VEE| (default min) a starting value for the slider
expand - (default null or 10 for mobile) set to value to expand the interactive area of the slider button
expandVertical - (default expand) set to value to expand the vertical interactive area of the slider button
expandBar - (default 20 or 0 for horizontal) set to value to expand the interactive area of the slider bar
expandBarVertical - (default 0 or 20 for horizontal) set to value to expand the vertical interactive area of the slider bar
useLabels - (default false) - add Labels to ticks if useTicks is true - can apply STYLE
labelMargin - (default 20) - distance from ticks to Label if useLabels is true
labelColor - (default 20) - distance from ticks to Label if useLabels is true
range - (default null) make the slider a range slider with two circle buttons
this will provide read and write rangeMin, rangeMax and rangeAve values instead of value
also will provide a read only rangeAmount
rangeBar, rangeSliderA, rangeSliderB, rangeButtonA and rangeButtonB properties will be added
rangeColor - (default purple) set the color of the range bar
rangeWidth - (default 3 pixels wider than the barWidth on both sides) set the thickness of the range bar (not its lenght)
rangeMin - (default min) set the minimum value of the range
rangeMax - (default (max-min)/2) set the maximum value of the range
rangeAve - (default null) set the range average value - this may relocate rangeMin and rangeMax settings
addZero - (default false) add zero on end of decimals for useLabels true
currentValue - same as value - kept in for backwards compatibility
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
value - gets or sets the current value of the slider
currentValue - same as value - kept in for backwards compatibility
valueEvent - gets or sets the current value and dispatches a "change" event if set and changed
min, max, step - read only - the assigned values
bar - gives access to the bar Rectangle
button - gives access to the Button
ticks - gives access to the ticks (to position these for example)
labels - access to the labels container if useLabels is true
accent - gives access to the access Shape
accentBacking - gives access to the accessBacking Shape
keyArrowsH, keyArrowsV - get or set the type of arrow keys to use (helpful for when cloning)
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
*** the following properties are added if the range parameter is true
rangeBar - access to the ZIM Rectangle that makes the bar between the range buttons
rangeSliderA - access to the first slider made - which is the same as this (the Slider object)
rangeSliderB - access to the second slider made which is a ZIM Slider added to this slider with the bar, ticks, labels, accents removed
rangeButtonA - access to the first slider's button - so the same as button
rangeButtonB - access to the second slider's button - so the same as ranageSilderB.button
rangeMin - get or set the minimum value of the range
in some cases, it may be better to animate the rangeSliderA.value and rangeSliderB.value
rather than the rangeMin and rangeMax for instance when wiggling to avoid crossover issues
rangeMax - get or set the maximum value of the range
rangeAve - get or set the average value of the range
rangeAmount - read only get the range amount
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
EVENTS
dispatches a "change" event when button is slid on slider (but not when setting value property)
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Selector
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A Selector acts on a ZIM Tile to provide an interactive selector that highlights a tile element.
The selector works as a select bar and a select pad.
See: https://zimjs.com/ten/wrapper.html which includes several Selector objects as bars
Selector as a pad would be similar to selecting letters on an onscreen TV remote system
Selector has a multi parameter that allows for multiple elements to be in selected mode.
The index or selectedItem will only be the last selected.
And only one selecteIndex can be set at a time
but as many as desired can be set one after another - in a loop for instance.
The difference is that once selected, the item remains highlighted until unselected with a presseup.
This allows for a synth pad for instance where multiple notes can be played at the same time.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// the items in the Tile should be centerReg()
new Selector(new Tile(new Rectangle().centerReg(), 4, 4, 20, 20))
.center()
.change(e=>{
e.target.currentItem.alpha = 0;
S.update();
});
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
tile - (default four red circles) the ZIM Tile to which to apply the selector
the elements should have their registration centered
see Tile for how to tile a series of different objects, etc.
this will work as a horizontal or vertical bar or a grid selector
borderColor - (default white) the border color of the selector
borderWidth - (default 2) the border width of the selector
backgroundColor - (default "rgba(0,0,0,.1)") the background color of the selector
corner - (default 10) the corner radius of the selector
dashed - (default false) the dashed border setting of the selector
paddingH - (default half tile spacingH) the space from the selected item
paddingV - (default half tile spacingV) the background color of the selector
speed - (default 2) the speed the selector moves to the next selection - can set to 0 for instant
diagonal - (default false) defaults to animate horizontally and vertically - set to true for diagonally
dim - (default null) set to true for .7 alpha or a number between 0-1 for tile to dim while selector animates
multi - (default false) set to true to enable multiple highlights
index and selectedItem will still read only the last selected tile or set only one tile at a time
will need a multitouch devices - degrades fine to single touch if no multitouch
keyArrows - (default true) set to false to disable keyboard arrows
behind - (default false) set to true to put selector behind tile
resizeScale - (default false) set to true to resize the border as selector changes scale
index - (default 0) the item index on which to start the selector - set to -1 for no selection
liveIndex - (default false) set to true to update the index and dispatch a change event as selector animates across items
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - the index number of the selected item in the tile - set to -1 for no selection
liveIndex - gets or sets whether to update the index and dispatch a change event as selector animates across items
currentItem - gets or sets the current item under the selector
noAnimate - set to make the next index or currentItem call not animate to tile
MULTI - in a change event with multi set:
downIndex - this will be the index under the selector on press down (or null if pressing up)
upIndex - this will be the index under the selector on press up (or null if pressing down)
downItem - this will be the item under the selector on press down (or null if pressing up)
upItem - this will be the item under the selector on press up (or null if pressing down)
lastIndex - get the last selected index
lastItem - get the last selected item
selectedCol - get the index of the selected column
selectedRow - get the index of the selected row
lastCol - get the index of the last selected column
lastRow - get the index of the last selected row
tile - a reference to the Tile object
selector - a reference to the Rectangle object used as the selector
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event when selector finishes animating to a new selection or for each index if liveIndex is true
dispatches a "changeset" event if index or currentItem is set programatically (not user selected)
note that a tap() or mousedown/click function can be used if the index is desired right away
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Dial
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A traditional dial - will give values back based on min and max and position of dial.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
var dial = new Dial({step:1, backgroundColor:"violet"})
.center()
.change(()=>{
zog(dial.value); // 1-10 in steps of 1
});
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
min - |ZIM VEE| (default 0) the minimum value for the dial
max - |ZIM VEE| (default 10) the maximum value for the dial
step - |ZIM VEE| (default 1) 1 provides steps of 1, 0 is continuous decimal, 2 would provide steps of 2, etc.
width - (default 100) the width of the dial (diameter)
backgroundColor - (default granite) the background color of the dial
indicatorColor - (default licorice) the color of the indicator
indicatorScale - (default 1) the scale of the indicator
indicatorType - (default "arrow" or "triangle") can also be "dot" or "circle", and "line" or "rectangle"
useTicks - (default true - unless step set to 0) will show lines for ticks
innerTicks (default false) set to true to put the ticks inside if step is set
tickColor - (default backgroundColor) set the tick color if ticks are set
tickStep - (default step - or 1 if no step and useTicks is true) set to adjust tick amount
semiTicks - (default 0) add a number of semiTicks. 1 would add one smaller tick between ticks, 4 would add 4 smaller ticks, etc.
tickScale - (default 1) scale the height of the ticks
semiTickScale - (default 1) scale the height of the semiTicks
innerCircle - (default true) gives an inner knob look - set to false for flat
innerScale - (default 1) can be adjusted along with indicatorScale to get a variety of looks
innerColor - (default "rgba(0,0,0,.2)") color of first inner circle
inner2Color - (default "rgba(0,0,0,.1)") color of inside inner circle
accentSize - (defualt 0) height of a ring around the dial that can be used to accent selection
accentOffset - (default .45 width/2) distance from edge of dial the accent will show
accentColor - (default zim.pink) color of filled part of accent
accentBackgroundColor - (default clear) color of background of accent
accentDifference - (default -.25) pixels accent background is bigger (or smaller if negative) than accentSize
this is used to stop bleeding of accent background
but can also be used to make the accent half the width of the background so it runs in a track, etc.
or fatter than the background so it runs on a wire or mono-rail
sound - (default false) - set to true to rotate dial -180 and set a gap of .25
adjusts various defaults for ticks, accent, indicatorType, etc.
linear - (default false - unless sound is true) - set to true to pressdrag up and down to increase and decrease dial
gap - (default 0) ratio of circle 360 to leave as a gap between dial start and dial end
limit - (default true) stops dial from spinning right around - set to false to not limit dial
keyArrows - (default true) set to false to disable keyboard arrows
keyArrowsStep - (default 1% of max-min) number to increase or decrease value when arrow is used
if step is set, then this value is ignored and set to step
keyArrowsH - (default true) use left and right arrows when keyArrows is true
keyArrowsV - (default true) use up and down arrows when keyArrows is true
continuous - (default false) this turns the dial into a continuous dial from the min at the top
The (max-min)/360 give a delta value per degree
and as the dial goes clockwise it adds the delta and as it goes counterclockwise it subtracts the delta
The steps are still used or not if set to zero
The min and max are no longer a real min and max - see the continuousMin and continuousMax below
limit is ignored or set to false when continuous is true
continuousMin - (default null) set to Number to limit the minimum total value of the dial when continuous is true
continuousMax - (default null) set to Number to limit the maximum total value of the dial when continuous is true
damp - (default null) set to value such as .1 to damp the slider value
IGNORED when limit set to false - otherwise may damp incorrectly
use with Ticker rather than "change" event - eg:
Ticker.add(function () {circle.x = slider.value;});
value - |ZIM VEE| (default min value) - set the value at start
useLabels - (default false) - add Labels to ticks if useTicks is true - can apply STYLE
labelMargin - (default 10) - distance from ticks to Label if useLabels is true
addZero - (default false) add zero on end of decimals for useLabels true
currentValue - same as value - kept in for backwards compatibility
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
value - gets or sets the current value of the dial
currentValue - same as value - kept in for backwards compatibility
valueEvent - gets or sets the current value and dispatches a "change" event if set and changed
min, max - read only assigned values unless continuous is true - then write enabled
step - read only - the assigned values
continuous - gets a boolean as to whether the continuous is true (read only)
continuousMin - get or set the continuousMin if continuous is set to true
continuousMax - get or set the continuousMax if continuous is set to true
backing - gives access to the dial backing Circle
inner and inner2 give access to any inner circles
ticks - gives access to the ticks (to scale these for example)
labels - access to the labels container if useLabels is true
accent - gives access to the access Shape
accentBacking - gives access to the accessBacking Shape
indicator - gives access to the indicator container with registration point at the dial center
indicatorShape - gives access to the shape on the end of the indicator (zim Triangle, Circle, Rectangle)
keyArrowsH, keyArrowsV - get or set the type of arrow keys to use (helpful for when cloning)
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
veeObj - an object with ZIM VEE original parameters:value allowing the ZIM VEE values to be referenced
for instance, obj.prop = Pick.choose(obj.veeObj.prop); will reset the the prop to the result of the original ZIM VEE value
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
EVENTS
dispatches a "change" event when dial changes value (but not when setting value property)
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Tabs
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A traditional tab layout for along the edge of content.
Can also act as an independent button row or column.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
var tabs = new Tabs({tabs:["A", "B", "C", "D"], spacing:5, corner:14})
.center()
.change(()=>{
zog(tabs.index);
zog(tabs.text);
});
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 240) overall width of tab set (ZIM divides the width across tabs and spacing)
height - (default 60) height of tabs
tabs - (default ["1","2","3","4"]) an array of any String, Number, Label, Button, (or any DisplayObject)
OR tab objects with the following properties available:
any tab specific properties will override the default values from other parameters
[{label:"String", width:200, backgroundColor:red, rollBackgroundColor:pink, downBackgroundColor:purple, selectedBackgroundColor:grey, color:yellow, selectedColor:"lime", downColor:white}, {etc.}]
label can be a String or a Label object - default text color is white
Tab objects can also include wait properties for individual buttons.
(this was put in place before Buttons were allowed in the tabs array - so you can just add a Button to the tab array instead)
See wait, waitTime, waitBackgroundColor, rollWaitBackgroundColor, waitColor, rollWaitColor, waitModal and waitEnabled parameters below
wait can be used with button's waiting property to offer an alternative to a loading screen or confirmation panel
also see the button's clearWait() method to cancel the wait state and waited event that triggers when the wait is done
wait will primarily be applicable when the tabs are used as a set of buttons rather than traditional tabbing
Warning - do not use the same array for multiple tabs as the array is turned into an array of objects used by the Tabs object.
backgroundColor - (default tin) the background color of a deselected tab when not rolled over
rollBackgroundColor - (default grey) the rollover background color
downBackgroundColor - (default null) the pressing down background color
selectedBackgroundColor - (default dark) the background color of the selected tab (any CSS color)
selectedRollBackgroundColor - (default rollBackgroundColor) the background color of the selected tab on rollover (if currentEnabled is true)
color - (default white) the text color of a deselected tab when not rolled over
rollColor - (default color) the rollover color (selected tabs do not roll over)
downColor - (default null) the pressing down color
selectedColor - (default color) the text color of the selected tab (any CSS color)
selectedRollColor - (default rollColor) the text color of the selected tab on rollover (if currentEnabled is true)
vertical - (default false) set to true to make vertical tabs with text still horizontal
spacing - (default 1) is the pixels between tab buttons
currentEnabled - (default false) set to true to be able to press (a second time) the selected tab button
currentSelected - (default true) set to false to not highlight the current button (good for button bars)
setting this to true will set currentEnabled to true
corner - (default 0) the corner radius of the tabs
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
base - (default "none") specifiy a side for flat bottom when corner is set (but not set to an array)
other values are "bottom" (default when corner and not vertical), LEFT (default when corner and vertical), TOP, RIGHT
** this was flatBottom - but then vertical tabs were added so it was changed in ZIM 9.2.0
keyEnabled - (default true) so tab key cycles through tabs, shift tab backwards
gradient - (default null) 0 to 1 (try .3) adds a gradient to the tabs
gloss - (default null) 0 to 1 (try .1) adds a gloss to the tabs
wait - (default null) String text for tab to say when pressed to enter a wait mode
The wait parameters can be (and probably will be) set as properties for each individual tab in the tabs array
waitTime - (default 20000) milliseconds to stay in wait state before returning to normal tab
waitBackgroundColor - (default color) the color of the tab during wait period
rollWaitBackgroundColor - (default color) the color of the tab during wait period
waitBackgroundColor - (default red) color to make button during wait time if wait is set
rollWaitBackgroundColor - (default rollColor) color for button when waiting and rolled over
waitColor - (default label's color) color to make text during wait time if wait is set
rollWaitColor - (default label's roll color) color for text when waiting and rolled over
waitModal - (default false) set to true to exit wait state if user clicks off tabs or to another tab
waitEnabled - (default true) set to false to disable tabs while in wait mode
backdropColor - (default null) set to a color to show behind the tabs (handy for when corner is not 0)
align - (default CENTER) horizontal align
valign - (default CENTER) vertical align
labelAlign - (default CENTER) horizontal align of the label only
labelValign - (default CENTER) vertical align of the label only
labelIndent - (default indent) indent of label when align or valign is set - usually same as indent unless custom objects are in tabs
labelIndentH - (default indent) horizontal indent of label when align or valign is set
labelIndentV - (default indent) vertical indent of label when align or valign is set
indent - (default 10) indent of items when align or valign is set and there are custom objects in tabs
useTap - (default false) set to true to use tap to activate otherwise uses ACTIONEVENT (mousedown or click)
excludeCustomTap - (default false) set to true to exclude custom buttons from tap() which would override existing tap() on the buttons
index - (default 0) - set the index at start
for no selected tab to start set this to -1
styleLabels - (default false) - set to true to pass styles to Tab labels
keyWrap - (default true) - set to false to not wrap around Tabs when tab key reaches end or start
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
addAt(items, index, setStyle) - an array of items to insert at an index in the tab - tabs will grow in size - returns the object for chaining
To keep the same size - run insertAt() and then remake the Tabs using the tabs.buttons array as the tabs parameter
Can also send in a setStyle object literal {} with color, rollColor, selectedColor and selectedRollColor plus the background color versions of these!
removeAt(number, index) - remove number of items starting at a an index (default 1, length-1) - tabs will shrink in size - returns the object for chaining
first() - select first tab - returns object to chain
last() - select last tab - returns object to chain
getItemIndex(item) - gets the index of the list item provided
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets or sets the selected index of the tabs
selected - gets the selected button - selected.enabled = true, etc.
tabs - gets or sets tabs object (will have to manually change buttons as well as adjust props)
backgroundColor - gets or sets default unselected background color - not applied to custom buttons
rollBackgroundColor - gets or sets default rolled over background color - not applied to custom buttons
selectedBackgroundColor - gets or sets default selected background color - not applied to custom buttons
selectedRollBackgroundColor - gets or sets default selected roll background color - not applied to custom buttons
color - gets or sets default unselected text color - not applied to custom buttons
rollColor - gets or sets default rolled over text color - not applied to custom buttons
selectedColor - gets or sets default selected text color - not applied to custom buttons
selectedRollColor - gets or sets default selected roll text color - not applied to custom buttons
text - gets current selected label text
label - gets current selected label object
buttons - an array of the ZIM Button objects. buttons[0].enabled = false;
labels - an array of the ZIM Label objects. labels[0].text = "YUM"; labels[2].y -= 10;
buttonDown - the button that is currently being pressed
backdrop - reference to backdrop Rectangle if backdropColor is provided
keyEnabled - gets or sets whether the tab key and shift tab key cycles through tabs (does not affect accessibility)
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when a tab changes (but not when setting index property)
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
Pad
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A pad that has rows and cols made of square keys.
When the keys are pressed the pad will dispatch a change event - get the index or text property.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
var pad = new Pad()
.center()
.change(()=>{
zog(pad.index); // 0-8
zog(pad.text); // 1-9
});
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
** inherits STYLE from type selector for Pad, then general styles then type selector for Tabs
width - (default 150) overall width of pad (ZIM divides the width across cols and spacing)
cols - (default 3) the columns in the pad
rows - (default cols) the rows in the pad
keys - (default an Array for cols x rows) an array of key objects with the following properties available:
any key specific properties will override the default values from other parameters
[{label:"String", width:200, backgroundColor:red, rollBackgroundColor:pink, selectedBackgroundColor:grey}, {etc.}]
the label can be a String or a Label object - default text color is white
Key objects can also include wait properties for individual buttons.
See wait, waitTime, waitBackgroundColor, rollWaitBackgroundColor, waitColor, rollWaitColor, waitModal and waitEnabled parameters below
wait can be used with button's waiting property to offer an alternative to a loading screen or confirmation panel
also see the button's clearWait() method to cancel the wait state and waited event that triggers when the wait is done
backgroundColor - (default tin) the background color of a deselected key when not rolled over
rollBackgroundColor - (default grey) the rollover background color (selected keys do not roll over)
downBackgroundColor - (default null) the pressing down background color
selectedBackgroundColor - (default dark) the background color of the selected key (any CSS color)
color - (default white) the text color of a deselected key when not rolled over
rollColor - (default color) the rollover color (selected keys do not roll over)
downColor - (default null) the pressing down color
selectedColor - (default color) the text color of the selected key (any CSS color)
spacing - (default 1) is the pixels between key buttons
currentEnabled - (default true) set to false to make selected key not pressable
currentSelected - (default true) set to false to make the current selected key not the selected colors
corner - (default 0) the corner radius of the keys
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
labelColor - (default white) the color of the label
gradient - (default null) 0 to 1 (try .3) adds a gradient to the tabs
gloss - (default null) 0 to 1 (try .1) adds a gloss to the tabs
wait - (default null) String text for button to say when pressed to enter a wait mode
The wait parameters can be (and probably will be) set as properties for each individual button in the pads array
waitTime - (default 20000) milliseconds to stay in wait state before returning to normal button
waitBackgroundColor - (default color) the color of the button during wait period
rollWaitBackgroundColor - (default color) the color of the button during wait period
waitBackgroundColor - (default red) color to make button during wait time if wait is set
rollWaitBackgroundColor - (default rollColor) color for button when waiting and rolled over
waitColor - (default label's color) color to make text during wait time if wait is set
rollWaitColor - (default label's roll color) color for text when waiting and rolled over
waitModal - (default false) set to true to exit wait state if user clicks off the pad or to another button
waitEnabled - (default true) set to false to disable pad while in wait mode
index - (default 0) - set the index at start
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets or sets the selected index of the pad
text - gets current selected label text
selected - gets the selected button - selected.enabled = true, etc.
label - gets current selected label object
selectedBackgroundColor - gets or sets default selected background color
backgroundColor - gets or sets default unselected background color
rollBackgroundColor - gets or sets default rolled over background color
color - gets or sets default unselected text color
rollColor - gets or sets default rolled over text color
selectedColor - gets or sets default selected text color
buttons - an array of the ZIM Button objects. buttons[0].enabled = false;
labels - an array of the ZIM Label objects. labels[0].text = "YUM"; labels[2].y -= 10;
tabs - an array of the zim Tabs objects (one object per row)
enabled - default is true - set to false to disable
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when a pad changes (but not when setting index property)
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
NumPad
zim class - extends a zim.Panel which extends a zim.Container which extends a createjs.Container
DESCRIPTION
A number pad that can be used on its own or with the ZIM Keyboard() which has a key at the bottom right to pop up the NumPad
The Keyboard can also be shown with the NumPadOnly parameter set to true to make use of the labels parameter to target labels.
See https://zimjs.com/zim/numpad.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const label = new Label("").pos(0,100,CENTER);
// The NumPad is built in to the Keyboard
// To set the parameters, such as titleBar, use STYLE before making the Keyboard
STYLE = {titleBar:"CALCULATE", align:CENTER};
const keyboard = new Keyboard({
labels:label,
numPadScale:.75,
numPadOnly:true,
numPadAdvanced:true
}).show();
keyboard.numPad.mov(0,120);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
advanced - (default false) set to true to add one more row of round brackets, exponential and percent or modulus
or set to "simple" to show only numbers, backspace and return
titleBar - |ZIM VEE| (default "NUMPAD") a String or ZIM Label title that will be presented on a titleBar across the top
titleBarColor - |ZIM VEE| (default black) the text color of the titleBar if a titleBar is requested
titleBarBackgroundColor - |ZIM VEE| (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - (default fit label) the height of the titleBar if a titleBar is requested
backgroundColor - |ZIM VEE| (default lighter) background color (use clear - or "rbga(0,0,0,0)" for no background)
borderColor - |ZIM VEE| (default pewter) border color
borderWidth - (default 1) the thickness of the border
corner - (default 15) the round of corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
numberCorner (default 30) the corner of the number keys
close - (default false) - add a close icon top right
closeColor - (default titleBarColor) the color of the close icon
collapse - (default false) - set to true to add a collapse icon to the titleBar that reduces the panel so only the bar shows and adds an icon to expand
also can double click bar to collapse panel
collapseColor - (default grey) - the color of the collapse icon
collapsed - (default false) set to true to start the panel collapsed
align - (default LEFT) set to CENTER, MIDDLE or "right" to align the label on the titleBar
this may get in the way of the close, arrow, collapse or extra buttons at right
shadowColor - (default "rgba(0,0,0,.3)" if shadowBlur) the shadow color - set to -1 for no shadow
shadowBlur - (default 14 if shadowColor) the shadow blur - set to -1 for no shadow
draggable - (default true if titleBar) set to false to not allow dragging titleBar to drag window
boundary - (default null) set to ZIM Boundary() object - or CreateJS.rectangle()
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
see ZIM Panel methods like collapse()
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
key - the last key pressed - also see the pressed event
this may include special colored keys: "clear", "space", "backspace" and "enter"
pad - the ZIM Pad used for the numbers - see ZIM Pad() for properties to access buttons, and labels
ALSO
see ZIM Panel properties like contentContainer, collapsed, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "pressed" event when pressed - also see the key property to give the text of the key pressed
dispatches a "close" event when closed with close button if there is a close button
dispatches a "collapse" event if collapsing
dispatches a "expand" event if expanding after being collapsed
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
DPad
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A DPad (Directional Pad) can be used to control x and y values
This is primarily handy on mobile where a substitute for keypresses is needed
The DPad can be set up for all directions, horizontal or vertical
The DPad can be passed in to a ZIM MotionController to control an object
See: https://zimjs.com/ten/dpad.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const dPad = new DPad().pos(50,50,LEFT,BOTTOM);
new MotionController({
target:new Circle().center(),
type:dPad,
speed:mobile()?100:80,
boundary:new Boundary(0,0,W,H)
});
S.update();
EXAMPLE
// importing zim_physics...
const physics = new Physics(0);
const ball = new Circle().center().addPhysics();
const dPad = new DPad().pos(40,40,LEFT,BOTTOM);
ball.control(dPad, 80);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
axis - (default ALL) set to HORIZONTAL or VERTICAL or BOTH. Appropriate arrows will show
width - (default 100) width of DPad
backgroundColor - (default granite) the background color (any zim or html color)
indicatorColor - (default moon) the color of the arrows
indicatorPressColor - (default lighter) the color of the arrows as pressed
indicatorScale - (default 1) the scale of the arrows
indicatorRadius - (default null) set the indicator radius
innerCircle - (default true) set to false to not show an inner circle
innerScale - (default .5) the scale relative to the indicator
activeRadius - (default width*2) radius at which the DPad works
clamp - (default true) set to false to not limit the value between -1 and 1
logo - (default false) set to true to show the letter D in the DPad - or add your own
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
dirX, dirY - the x and y values for the DPad - between -1 and 1 if clamp is set
these can be multiplied by a factor to adjust speed - or use speed parameter of associated MotionController
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
enabled - default is true - set to false to disable
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event with dirX and dirY provided as well on the event object
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Radial
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A radial ring with selectable buttons with lables or icons
Used internally by ZIM RadialMenu which has expandable rings for a hierarchical interface
Radial uses LabelOnArc for labels
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
var radial = new Radial(["one", "two", "three", "four"])
.center()
.change(()=>{
zog(radial.index);
});
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
labels - (default ["A", "B", "C", "D", "E"]) an array of text or ZIM Label objects for buttons
size - (default 30) label size
font - (default "verdana") the font - can also import fonts in Frame() asset parameter or F.loadAssets()
startAngle - (default null) will start first button centered at top - see also totalAngle
setting an angle will start left side of first button at this angle
with 0 being the top (note, ZIM angles usually start along x axis - but not here)
totalAngle - (default 360) set to use only a portion of the circle - see also startAngle
angles - (default null) can set an array of angles for center of the buttons
can use angles property toString() to get existing angle data
this can be modified to suit and passed into this parameter for unequal button sizes
flip - (default true) flip the text between 90 and -180 (from 0 at top)
shiftRadial - (default 0) amount to shift text in radially
icons - (default null) set to an array of objects that will go under the text
can set the labels to ["", "", "", etc.] to hide the text
icons should be centerReg({add:false}) to ensure centered placement
rollIcons - (default null) set to an array of objects to replace icon when rolled over
rotateIcons - (default false) set to true to rotate icons around radial
iconsShiftRadial - (default 0) amount to shif the icons radially
height - (default 60) height of radial - not including core
coreRadius - (default 100) the radius of the core
this is fairly large but can sca(.5) the radial after creating, etc.
coreColor - (default dark) the color of the core
backgroundColor - |ZIM VEE| (default granite) the background color of a button
ZIM VEE means you can specify different colors for instance: series(blue, green, red, yellow)
these would then be the color order of the buttons - same for rollBackgroundColor, etc.
rollBackgroundColor - |ZIM VEE| (default tin) the rollover background color of a button
selectedBackgroundColor - |ZIM VEE| (default charcoal) the background color of the selected button
selectedRollBackgroundColor - |ZIM VEE| (default selectedBackgroundColor) the roll background color of the selected button
backdropColor - (default clear) set to change the color behind the radial - including spacingOuter
color - |ZIM VEE| (default white) the text color of the button
rollColor - |ZIM VEE| (default color) the rollover text color of the button
selectedColor - |ZIM VEE| (default color) the text color of the selected button
selectedRollColor - |ZIM VEE| (default color) the rollover text color of the selected button
borderColor - (default dark) color of the button border
borderWidth - (default 2) width of the button border
gradient - (default null) set to a number between 0 and 1 - would suggest .1 for gradient on button
gap - (default 6 pixels or 3 degrees if gapAsAngle is true) gap between buttons
gapAsAngle - (default false) set to true set gap as angle
spacing - (default 6) radial spacing around button from core or edge of backdrop
spacingInner - (default spacing) inside radial spacing from core
spacingOuter - (default spacing) outside radial spacing from edge of backdrop
currentEnabled - (default false) set to true to make selected key pressable (for change event)
currentSelected - (default true) set to true to make selected key show selected colors
index - (default 0) - set the index at start
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets or sets the selected index of the pad
text - gets current selected label text
label - gets current selected label object
selected - gets the selected button - selected.enabled = true, etc.
buttons - a container of buttons
each button has label and icon properties
angles - an array of angles to the center of the buttons
can log angles.toString() to get angle data
this can be adjusted and passed in to the angles parameter for unequal size buttons
core - a reference to the core circle object
backdrop - a reference to the backdrop circle
enabled - default is true - set to false to disable
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when the button changes (but not when setting index property)
see also currentEnabled to get change event for each press - or use tap()
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
RadialMenu
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
An expanding hierarchy menu of button rings - using ZIM Radial objects.
The menu is specified by a menu parameter in the format of a ZIM Hierarchy object.
Styles for each ring can be specified in the menu object.
Icons for each ring can be specified in the styles.
See https://zimjs.com/ten/radial.html (ZIM TEN)
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const menu = {
"one":[1,2,3,4], // an array is okay as all items are leaf nodes (end nodes)
"two":{ // an object literal is required as one or more items hold other items
"1":[], // this holds nothing (a leaf node) but still needs an empty array
"2":["a", "b", "c"], // this holds a linear list - all leaf nodes
"3":{ // this holds another nested list where at least one item holds more
"emotions":["love","hate","happy","sad"],
"flavors":["sweet","sour","bland","spicy"]
}
},
"three":[1,2,3,4,5,6],
"four":[1,2,3,4,5,6,7,8]
}
new RadialMenu(menu).sca(.5).center();
// OR ADD STYLES
// see https://zimjs.com/ten/radial.html for full example (ZIM TEN)
// any Radial parameters can go in the styles:{} brackets
// including icons and rollIcons
// and can use series to apply background colors and colors to individual buttons
// PS - this is the EXTRA version of the simple ZIM Hierarchy format
// here we pass styles as an extra property - list is required
// styles is optional but used by ZIM RadialMenu to apply associated styles
var menu = {
list:{
"one":{
list:["A","B","C","D"], // an array is okay as all items are leaf nodes (end nodes)
styles:{backgroundColor:blue}
},
"two":{
list:{ // an object literal is required as one or more items hold other items
"1":[], // this holds nothing (a leaf node) but still needs an empty array
"2":{
list:["a", "b", "c"], // this holds a linear list - all leaf nodes
styles:{}
},
"3":{ // this holds another nested list where at least one item holds more
list:{
"emotions":{
list:["love","hate","happy","sad"],
styles:{}
},
"flavors":{
list:["sweet","sour","bland","spicy"] ,
styles:{}
}
},
styles:{}
}
},
styles:{}
},
"three":{
list:[1,2,3,4,5,6],
styles:{}
},
"four":{
list:[1,2,3,4,5,6,7,8],
styles:{}
}
},
// the styles for the first list
// here we make each backgroundColor a different color
styles:{backgroundColor:series(red,green,blue,yellow)}
}
new RadialMenu(menu).sca(.5).center();
S.update();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports VEE - parameters marked with ZIM VEE mean a zim Pick() object or Pick Literal can be passed
Pick Literal formats: [1,3,2] - random; {min:10, max:20} - range; series(1,2,3) - order, function(){return result;} - function
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
menu - (default a simple menu) a ZIM Hierarchy (simple, simple EXTRA or complex)
that holds the menu labels and optionally styles
see the ZIM RadialMenu examples and the format descriptions of ZIM Hierarchy for details
size - (default 30) label size
font - (default "verdana") the font - can also import fonts in Frame() asset parameter or F.loadAssets()
startAngle - (default null) will start first button centered at top - see also totalAngle
setting an angle will start left side of first button at this angle
with 0 being the top (note, ZIM angles usually start along x axis - but not here)
totalAngle - (default 360) set to use only a portion of the circle - see also startAngle
flip - (default true) flip the text between 90 and -180 (from 0 at top)
shiftRadial - (default 0) amount to shift text in radially
rotateIcons - (default false) set to true to rotate icons around radial
iconsShiftRadial - (default 0) amount to shif the icons radially
height - (default 60) height of radial - not including core or previous radials
coreRadius - (default 100) the radius of the core
this is fairly large but can sca(.5) the radial after creating, etc.
coreColor - (default dark) the color of the core
title - (default "MENU") the label text in the core
titleIcon - (default null) an object to put under the title
** FOR BELOW: see menu parameter where colors can be set per ring and per button for ZIM VEE colors
backgroundColor - |ZIM VEE| (default granite) the background color of a button
ZIM VEE means you can specify different colors for instance: series(blue, green, red, yellow)
these would then be the color order of the buttons - same for rollBackgroundColor, etc.
rollBackgroundColor - |ZIM VEE| (default tin) the rollover background color of a button
selectedBackgroundColor - |ZIM VEE| (default charcoal) the background color of the selected button
selectedRollBackgroundColor - |ZIM VEE| (default selectedBackgroundColor) the roll background color of the selected button
backdropColor - (default clear) set to change the color behind the radial - including spacingOuter
color - |ZIM VEE| (default white) the text color of the button
rollColor - |ZIM VEE| (default color) the rollover text color of the button
selectedColor - |ZIM VEE| (default color) the text color of the selected button
selectedRollColor - |ZIM VEE| (default color) the rollover text color of the selected button
borderColor - (default dark) color of the button border
borderWidth - (default 2) width of the button border
gradient - (default null) set to a number between 0 and 1 - would suggest .1 for gradient on button
gap - (default 6 pixels or 3 degrees if gapAsAngle is true) gap between buttons
gapAsAngle - (default false) set to true set gap as angle
spacing - (default 6) radial spacing around button from core or edge of backdrop
spacingInner - (default spacing) inside radial spacing from nearest inside object
spacingOuter - (default spacing) outside radial spacing from edge of backdrop
currentEnabled - (default false) set to true to make selected key pressable (for change event)
currentSelected - (default true) set to true to make selected key show selected colors
open - (default false) set to true to start with first menu open
under - (default true) set to false to open menu rings in the top layer (usually under just in case there is a backdrop)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
closeRings(num) - close menu rings - default is all rings but use 1 to close the outer ring, 2 to close the two outer rings, etc.
see the outerLevel property for the current outer ring number with core being 0
opening rings programmatically is not yet supported but may be in the future
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - gets the selected index of the outer ring (setting may come soon)
selectedLevel - gets the index of the level with the latest selection - the core is 0
selectedMenu - gets a reference to the selected menu
outerLevel - gets the index number of the outside level - the core is 0
outerMenu - gets a reference to the outer menu
text - gets current selected label text
label - gets current selected label object
selected - gets the selected button
core - a reference to the core circle object
enabled - default is true - set to false to disable
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
OPTIMIZED
This component is affected by the general OPTIMIZE setting (default is false)
if set to true, you will have to S.update() after setting certain properties
and S.update() in change event to see component change its graphics
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches a "change" event when the button changes (but not when setting index property)
see also index, selectedLevel, selected and text properties
see also currentEnabled to get change event for each press - or use tap()
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
ColorPicker
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A traditional color picker which shows 256 Web colors by default or custom colors.
Can additionally show 16 greys and / or an alpha slider.
Picking on a color sets the swatch color and the selectedColor property.
OK dispatches a "change" event if the color changed or a close event if not.
The X dispatches a "close" event.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const cp = new ColorPicker()
.show() // use show() and hide() with ColorPicker. As of ZIM ZIM 01 can also use pos(), loc(), center(), etc.
.change(()=>{
zog(cp.selectedColor); // #ffcc99, etc. after pressing OK
zog(cp.selectedAlpha); // 0-1
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 500) the width of the color picker
colors - (default "spectrum") - this shows a color spectrum, drag bar with collapse, mode and close (if no buttonBar)
these can be configured with ColorPicker parameters (see spectrum parameter near end of parameters).
The mode toggles between a gradient and pixel blocks
Set the colors to "legacy" to show the traditional 256 colors
or pass in an optional list of colors ["red", "#CCC", etc.]
cols - (default 10) how many columns to use if you pass in custom colors
spacing - (default 2) is the space between the color squares
greyPicker - (default true unless one row) shows an extra 16 greys (set to false to hide these)
for the default colors it also includes 2 starting colors that record last picked colors
alphaPicker - (default true unless one row) shows an alpha slider (set to false to hide this)
the swatch has a black, grey and white backing underneath to show multiple alpha effects
startBackgroundColor - (default the last color in color array) the starting color
draggable - (default true (false if no buttonBar or no spectrum)) whether you can drag the component - set to false to not drag
a small grip under the color text shows if draggable
shadowColor - (default rgba(0,0,0,.3)) set to -1 for no drop shadow
shadowBlur - (default 14) the blur of the shadow if shadow is set
buttonBar - (default true unless one row) set to false to hide the button bar with OK and X (close)
circles - (default false) set to true to show colors in circles rather than squares
indicator - (default true) set to false to remove indicator from currentBackgroundColor
backgroundColor - (default black) the color of the background
keyArrows - (default true) set to false to disable keyboard arrows
container - (default zimDefaultFrame) if using show(), hide(), toggle() can set which container to center on
index - (default 0) - set the index at start
dropperTarget - (default null) - set to a DisplayObject to use dropper on the target - such as the stage
the dropper will always work on the spectrum
dropperTarget will cache the target so a color can be picked from it
but this is modal on the target so buttons, etc. cannot be used and animations will not be seen
spectrumCollapse - (default true) - if spectrum color is set, set to false to not show a collapse button
spectrumMode - (default true) - if spectrum color is set, set to false to not show a mode button
spectrumClose - (default true) - if spectrum color is set, set to false to not show a close button
spectrumOk - (default true) - if spectrum color is set and there is a buttonBar, set to false to not show an OK button
spectrumTitle - (default null) - if spectrum color then this is the title - for example, set to "Color Picker"
collapsed - (default false) - if spectrum and spectrumCollapse then set to true to start collapsed
tolerancePicker - (default false) - show a slider for tolerance - useful for when using ColorPicker to keyOut a color
note: this will automatically hide the alphaPicker
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show() - show the picker (returns the picker for chaining) (as of ZIM ZIM 01 can also use pos(), loc(), center(), etc.)
hide() - hides the picker (as of ZIM ZIM 01 can also use removeFrom())
toggle(state - default null) - shows if hidden and hides if showing (returns the picker for chaining)
or pass in true to show picker or false to hide picker
toggleSpectrum(state - default null) - if run without state will toggle the spectrum mode
or pass in true to show gradient or false to show pixel blocks
collapse(state - default true) - with the "spectrum" setting, set state to true (default) to collapse or false to expand the picker
updateDropperTarget() - with the "spectrum" setting, a cached view of the dropperTarger is shown to pick the color from
using updateDropperTarget() will update this cached view - it is processor intensive so beware
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
selectedColor - gets or sets the selected color swatch
value - same as selectedColor but consistent with other components
currentValue - same as value - kept in for backwards compatibility
valueEvent - gets or sets the current value and dispatches a "change" event if set and changed
selectedAlpha - gets or sets the selected alpha (set does not work if alphaPicker is false)
index - get or sets the selected index of the colorPicker
colors - read only array of colors in picker - not including greys - or "spectrum"
greys - read only array of greys in picker if the grey picker is set
toggled - read-only Boolean property as to whether picker is showing
collapsed - read-only Boolean property as to whether picker is collapsed
swatch - gets the Rectangle that is the color swatch
swatchBacking - gets the zim Shape that is under the swatch (seen if alpha set low)
swatchText - gets the Label that shows the color text
grip - gets the createjs.Shape for the grip if the panel is dragable
background - gets the Rectangle that is the background (cp.background.color = "white" - now a backgroundColor parameter)
okBut - references the OK Button
closeBut - references the X Button
indicator - gets the zim shape that is the indicator (if indicator is true)
title - reference to the spectrum title Label
NOTE
for colors:"spectrum"
dropper - reference to the circle dropper
gradient - reference to the gradient spectrum Bitmap
pixels - reference to the pixel spectrum Bitmap
closeIcon - reference to the close icon if there is one on the top bar
modeIcon - reference to the mode icon if there is one on the top bar
collapseIcon - reference to the collapse icon if there is one on the top bar
spectrumToggled - read-only Boolean that is true if gradient and false if spectrum is pixel blocks
NOTE
if alphaPicker is true:
alphaBacking - gets reference to the Rectangle that makes the backing for the alpha slider
alphaBut - the Button on the alpha slider
alphaSlider - the Slider for the alpha
alphaText - the Label for the alpha
NOTE
if tolerancePicker is true:
toleranceBacking - gets reference to the Rectangle that makes the backing for the tolerance slider
toleranceBut - the Button on the tolerance slider
toleranceSlider - the Slider for the tolerance
toleranceText - the Label for the tolerance
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
NOTE
these have been updated in ZIM 00
dispatches a "change" event when the color swatch changes or if no swatch when a color is picked.
also dispatches when the alpha is changed if there is an alpha picker.
also dispatches when the tolerance is changed if there is an tolerance picker.
also dispatches when text of color is changed.
dispatches a "swatch" event when the swatch is pressed.
dispatches an "ok" event when the OK button is pressed.
dispatches a "close" event when the close button is pressed. Automatically closes the ColorPicker.
dispatches a "collapsed" event when collapsed in spectrum color mode.
dispatches a "expanded" event when expanded in spectrum color mode.
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
EmojiPicker
zim class - extends a zim.Window which extends a zim.Container which extends a createjs.Container
DESCRIPTION
An Emoji picker panel.
Can customize the list of emojis.
Gives a zim Emoji object as currentEmoji property on a "change" event
SEE: https://zimjs.com/nft/bubbling/emoji.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const emojiPicker = new EmojiPicker()
.center()
.change(() => {
// we will make a bigger emoji by passing the code of the currentEmoji
// to the new Emoji - you can clone and then scale but that can look blotchy
const emoji = new Emoji(emojiPicker.currentEmoji.code, 200)
.centerReg()
.drag();
S.update();
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 400) the width of the window
height - (default 500) the height of the window
emojis - (default a big list!) an array of UTF codes for emojis
["\ud83d\udca5","\ud83c\udf35", etc.]
can view the code page https://zimjs.com/code.php?view=67.05 to get raw list to modify
monochrome - (default false) set to true to greyscale the emojis
this had better performance when Chrome made black and white emojis in a bold bug
too bad - hope they bring them back.
backgroundColor - (default lighter) background color (use clear - or "rbga(0,0,0,0)" for no background)
titleBar - (default "Emojis") a String or ZIM Label title for the panel that will be presented on a titleBar across the top
note: set STYLE = {titleBar:false, close:false} to turn off title bar and remove close button
titleBarColor - (default black) the text color of the titleBar if a titleBar is requested
titleBarBackgroundColor - (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - the height of the titleBar if a titleBar is requested
cache - (default false or true if mobile) - cache the collection of emojis for better performance - will not look as crisp on desktop
size - (default 30) - the size of the emojis in the picker
collapse - (default false) - set to true to add a collapse icon to the titleBar that reduces the window so only the bar shows and adds an icon to expand
also can double click bar to collapse window
collapseColor - (default grey) - the color of the collapse icon
collapsed - (default false) set to true to start the window collapsed
colSize - (default size+15) - the size of the columns
rowSize - (default size+14) - the size of the rows
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
see all the methods of the ZIM Panel
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
selectedEmoji - get the selected emoji - this is a zim Emoji object
clone the object to let the user use it
or make a new Emoji() from the selectedEmoji.code and pass in a different size, etc.
emojiData - get the list of emojis - warning, if zog to console they will look like emojis
wrapper - the ZIM Wrapper used for the picker
ALSO
see all the properties of the ZIM Panel including close, titleBar, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches an "emoji" event when an emoji is picked
dispatches a "closed" event when closed
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
TextEditor
zim class - extends a zim.Panel which extends a zim.Container which extends a createjs.Container
DESCRIPTION
A configurable text editor for a ZIM Label - or text in code memory.
Call the editor.show(label) method and pass in the label - it will let the user change the following properties:
text, color, bold, italic, align, size, and font
Which ones the editor uses can be set with parameters.
SEE: https://zimjs.com/cat/texteditor.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const label = new Label({
text:"press to edit with TextEditor",
italic:true,
align:CENTER,
font:"verdana"
})
.center()
.expand()
.tap(()=>{
textEditor.show(label);
});
const textEditor = new TextEditor({
colorList:true, // or array of colors
optionList:["bold","italic","align"], // or true, or array with any of these
sizeList:true, // or array of sizes
fontList:true, // or array of fonts
live:true, // default
scroll:true // default, etc.
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
The TextEditor is made of of the following sub components
and many styles need to be set on the sub component types:
Panel, TextArea, Button, ColorPicker, Selector, Stepper, List
For instance STYLE = {type:{Panel:{titleBarBackgroundColor:red}}}
width - (default 400) the width of the editor
color - (dark) the color of the TextArea text in the editor
backgroundColor - (default lighter) the background color of the editor
fieldColor - (default backgroundColor darkened .05) - the background color of the TextArea
fieldHeight - (default button height plus 2 margins) - the height of the TextArea
textSize - (default 20) the size of the text in the TextArea
sizeList - (default false) set to true to show numbers from 5-500
or set to an array of numbers used for the size Stepper [10,12,14,16] for instance
optionList - (default false) set to true to show ["bold", "italic", "align"]
or set to an array with any of these values ["bold", "italic"] for instance
colorList - (default false) set to true to show the default ZIM ColorPicker
or set to an array with colors [red, green, blue, black, "violet", "#333"] for instance
fontList - (default false) set to true to show a default list of fonts
"Arial",
"Courier New",
"Georgia",
"Helvetica",
"Palatino",
"Tahoma",
"Verdana",
// plus on desktop:
"Impact",
"Comic Sans"
or set to an array with desired fonts ["courier", "verdana"] for instance
live - (default true) will update the label as the text is typed
set to false to update only on button press - note, other setting update live regardless
button - (default green check) set to a custom ZIM Button if desired
titleBar - (default "Text Editor") a String or ZIM Label title for the panel that will be presented on a titleBar across the top
titleBarColor - (default black) the text color of the titleBar if a titleBar is requested
titleBarBackgroundColor - (default "rgba(0,0,0,.2)") the background color of the titleBar if a titleBar is requested
titleBarHeight - (default fit label) the height of the titleBar if a titleBar is requested
wrap - (default true) set to false to not wrap text in TextArea (wrapping on the actual label can be done with label.lineWidth)
limit - (default null) set to a number to limit the TextArea number of characters
scroll - (default true) set to false to not show a vertical scrollbar when needed - note if textHeight is not high enough, a scrollbar may not show
placeholder - (default null) set to true to show default text - will be overwritten with label text if there is text
password - (default false) set to true to make the TextArea a password field - shows dots - the label will not show dots
borderColor - (default pewter) border color
borderWidth - (default 1) the thickness of the border
margin - (default 10) the margin around the various sub components
corner - (default 0) the round of corner
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default "rgba(0,0,0,.3)" if shadowBlur) the shadow color - set to -1 for no shadow
shadowBlur - (default 14 if shadowColor) the shadow blur - set to -1 for no shadow
draggable - (default true if titleBar) set to false to not allow dragging titleBar to drag window
boundary - (default null) set to ZIM Boundary() object - or CreateJS.rectangle()
frame - (default zdf - ZIM Default Frame) pass in a frame if not the default frame - lets TextArea and ColorPicker work
fontListHeight - (default 100) the height of the font list if there is one
fontListViewNum - (default 3) the number of fonts to show in the font list if there is one
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show(label, x, y, frame) - show the editor and pass in the label to operate on
the editor will appear centered above or below the text depending on where there is more room
this can be overridden with the x and y parameters
the TextEditor will show on the stage of the Label
if the label is not on the stage then the stage of the frame parameter otherwise the stage of the ZIMDefaultFrame
If the editor is already open it will not move
Calling show(label2) on a different label will switch the editor to that label
see also the label property
hide() - hides the editor
closeColorPicker() - close the ColorPicker - this needs to display the text (which is hidden when the ColorPicker opens)
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
see all the methods of the ZIM Panel
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
textArea - reference to the TextArea
label - get or set the label associated with the textEditor
button - reference to the Button
if various features are set:
swatch - reference to the Rectangle showing color
colorPicker - reference to the ColorPicker
bold - reference to the bold Button
italic - reference to the italic Button
align - reference to the align Selector
size - reference to the size Stepper
font - reference to the font List
ALSO
see all the properties of the ZIM Panel including close, titleBar, etc.
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
dispatches an "input" event when the text is changed - although default is to update live
dispatches an "update" event when any property is changed and where text is changed
dispatches a "set" event when button is pressed
dispatches a "close" event when closed
dispatches a "color" event when ColorPicker is opened
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Keyboard
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
The Keyboard class makes a keyboard ideal for mobile or touch screens.
Often, it seems the mobile keyboard can cause problems with layout.
This in-canvas keyboard requires much less testing and concern.
The Keyboard can work with ZIM Labels to give input text without a TextArea.
Thanks Frank Los for the initial design and coding of the Keyboard.
Keyboard also captures hard keyboard keydown and will type that as well
See https://zimjs.com/keyboardNOTE
press and hold down the vowels for multiple vowel options
NOTE
multi-line Label and TextArea input is not supported
NOTE
the width of the Label can be set by the Label's lineWidth paremeter
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// create Labels to capture the text from the keyboard
const text1 = new Label({text:"", backgroundColor:white}).pos(100,100);
const text2 = new Label({text:"", backgroundColor:white}).pos(100,200);
// create a new Keyboard and pass in the labels as an array
// or if just one label, then pass in the label
const keyboard = new Keyboard([text1, text2]);
// if just the letter is needed use the keydown event
keyboard.on("keydown", e=>{
zog(e.letter);
});
// create events to capture a mousedown on the labels
const text1Event = text1.on("mousedown", activate);
const text2Event = text2.on("mousedown", activate);
function activate(e) {
keyboard.show();
// remove the events when keyboard is active
text1.off("mousedown", text1Event);
text2.off("mousedown", text2Event);
}
keyboard.show(); // optionally show the keyboard to start
// add back the events to show the keyboard
keyboard.on("close", ()=>{
text1.on("mousedown", text1Event);
text2.on("mousedown", text2Event);
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
labels - (default null) a ZIM Label to show letters in or an array of labels
Keyboard will add a cursor to the Labels
and provide management across multiple labels
currently, multiline labels are not supported
setting the label lineWidth will set the max width of the label
backgroundColor - (default dark) an css color for the background color of the keys
color - (default white) the color of the text
shiftBackgroundColor - (default "orange") the color of the active shift key
shiftHoldBackgroundColor - (default "red") the color of the active shift hold key
placeBackgroundColor - (default "50c4b7") the color of the arrow backings when placing cursor in label
placeColor - (default "50c4b7") the color of the arrow text when placing cursor in label
cursorColor - (default "50c4b7") the cursor color
shadeAlpha - (default .2) special keys are shaded darker by this alpha
margin - (default 5) the margin around the keyboard from the container width
corner - (default 30) the round of the corner (set to 0 for no corner)
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
draggable - (default false) set to true to show the drag handle at top right
placeClose - (default true) shows an x key to close the cursor placement menu
shadowColor - (default "rgba(0,0,0,.2)") set to -1 for no shadow
shadowBlur - (default 14) how blurred the shadow is if the shadow is set
container - (default zimCurrentFrame stage) if placing Keyboard in different container or stage
data - (default see below) pass in data for the letters on the three sets of keyboards
also see the layout parameter for current default layouts like "arabic", "hebrew", etc.
Below is the default data - change any of the keys to change keyboard
There must be three boards (you can request more)
There must be a button specified on the fourth row to toggle to the second screen and back
There must be a button on the second and third screen at the start of the third row
to toggle between the second and third screen
The "shift" and "delete" keys are optional and can be moved or removed
There is a "back" key that is like the "backspace" key but takes the space of one key and not two keys
There will be at least 10 key places but there can be more than 10 keys per row
The last element of the outer array is a an object with special characters for e,u,i,o,a,n
If left off then it will use the characters below in the example.
These can be changed to any characters showing an extra set of any characters.
The fifth and sixth elements are lowercase to uppercase and uppercase to lowercase override mappings
For instance, in the turkish layout ı:"I" and i:"İ" for lowercase to uppercase
and I:"ı" and İ:"i" for uppercase to lowercase.
Use the data property to get this array if desired:
var data = [
[
["q","w","e","r","t","y","u","i","o","p"],
["a","s","d","f","g","h","j","k","l"],
["shift","z","x","c","v","b","n","m","backspace"],
["?123"] // rest of bottom line automatically added
],[
["1","2","3","4","5","6","7","8","9","0"],
["!","@","#","$","/","^","&","*","(",")"],
["1/2","-","'", "\"",":",";",",","?","backspace"],
["ABC"] // rest of bottom line automatically added
],[
["+","x","%","=","<",">","{","}","[","]"],
["€","£","¥", "$", "₩", "~", "`","¤","♡","☆"],
["2/2","_","\\","|","《","》","¡","¿","backspace"],
["ABC"] // rest of bottom line automatically added
],{
e:["ė","ē","ę","ê","é","ë","è"],
u:["ū","û","ú","ü","ù"],
i:["ī","į","ì","í","ï","î"],
o:["ō","œ","ø","õ","ô","ó","ö","ò"],
a:["ā","ã","å","â","á","ä","à","æ"],
n:["ñ","ń"]
},{
lowercaseletter:"uppercaseletter", // override lowercase to uppercase map
lc2:"uc2"
},{
uppercaseletter:"lowercaseletter", // override uppercase to lowercase map
uc2:"lc2"
}
];
place - (default true) set to false to not add place arrows when selecting Label
placeShiftH - (default 0) set to shift place arrows horizontal - from default location
placeShiftV - (default 0) set to shift place arrows vertically - from default location
placeScale - (default 1) set the place menu scale
special - (default null) set to a string to add a special key to the left of the space bar
rtl - (default false) (Experimental) set to true to use right-to-left text
hardKeyboard - (default true) set to false to not include keypresses from physical keyboard
layout - (default "qwerty") set to change the layout (also see data parameter for custom layout)
additionally supported layouts are "azerty", "hebrew", "turkish", "arabic" - thanks to those who submitted layouts!
please let us know at https://forum.zimjs.com if you are using a layout that others would use!
numPadScale - (default .8) the scale of the NumPad when pressed from the numPad key at bottom right
numPadDraggable - (default true) set to false to not be able to drag the NumPad
numPadOnly - (default false) set to true to open the NumPad only but can then use with labels
numPadAdvanced - (default false) set to true to add an extra row to the NumPad with round brackets, exponential and percent or modulus keys
maxLength - (default null) set to a number for the maximum characters - also see maxLength property
numbersOnly - (default false) set to force numbers only - also see numbersOnly property
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
show(index) - shows the Keyboard - use this rather than addTo(), etc.
index (default null) specify the index of the labels array to show cursor in
hide() - hides the keyboard
toggle(state - default null) - shows if hidden and hides if showing (returns the keyboard for chaining)
or pass in true to show keyboard or false to hide keyboard
setText(text) - change the current label text to the text provided
clearText() - clear the current label text
addChar(char) - add a character to the currentLabel at the currentIndex
removeChar() - removes the chararcter in the currentLabel at the currentIndex-1 (a backspace)
addLabels(labels) - add a ZIM Label or an array of Labels to the labels list for the Keyboard
removeLabels(labels) - remove a ZIM Label or an array of Labels
showNumPad() - shows the NumPad - also see Keyboard numPadOnly parameter and the NUMPAD key
hideNumPad() - hide the NumPad - also see the NUMPAD key and the x on the NumPad
showKeyboard() - specifically shows the keyboard if numPadOnly is set
hideKeyboard() - specifically hides the keyboard but may still show the NumPad
showPlace() - show the place menu for cursor
hidePlace() - hide the place menu for cursor
resize() - scales the keyboard to the stage with margin and places at bottom of screen
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a clone of the Keyboard
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
data - get the data array for the keyboard - see the data parameter for details and to set value for data
labels - get the labels array - use addLabels() and removeLabels() to set
selectedLabel - the label with the cursor or -1 if no cursor
index - the index of the cursor in the selected label or -1 if no cursor
toggled - read-only Boolean that is true if keyboard is visible and false if not
keys - reference to the keyboard itself
numPad - reference to the NumPad once it has been shown once
placeMenu - reference to the place menu
maxLength - get or set the maximum characters - will not change existing label
numbersOnly - get or set to force numbers only - will not change existing label
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
Dispatches a "keydown" event with an event object having a letter property
keyboard.on("keydown", function(e) {zog(e.letter);}); // logs letter pressed or "del" for delete
Dispatches a "special" event if the special parameter is used and the special key is pressed
Dispatches a "close" event when close keyboard icon at bottom right is pressed
Dispatches "numpadopen" and "numpadclose" events when the NumPad is opened or closed
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Organizer
zim class - extends a zim.Tabs which extends a zim.Container which extends a createjs.Container
DESCRIPTION
A Tabs bar of interface for organizing a ZIM List.
This includes add, up, down, toTop, toBottom and remove icon buttons.
The Organizer can sit above the list and allow the user to add, remove and reorder the list.
Adding an item will add an empty button - this would need to be filled with the user input, etc.
If the user input is not ready, the autoAdd parameter can be set to false.
The change event will report an orgType of "add" and the add() method can be used when the input is ready.
The same for positioning or removing if desired.
See: https://zimjs.com/explore/organizer.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const organizer = new Organizer(250)
.change(()=>{
if (organizer.orgType=="add") organizer.orgItem.text = "new";
});
new List({
width:250,
organizer:organizer // pass the organizer to the list
});
.center()
.mov(0,40);
// OR
const list = new List(250)
.center()
.mov(0,40);
var organizer = new Organizer(250, list)
.center()
.mov(0,-80)
.change(()=>{
if (organizer.orgType=="add") organizer.orgItem.text = "new";
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 300) width of Tabs - this will determine the height as the Buttons are square.
There is no vertical version of an Organizer.
list - (default null) an ZIM List object to control - or null to add later with the list property
useAdd - default(true) set to false to not include the add button
useRemove - default(true) set to false to not include the remove button
usePosition - default(true) set to false to not include the position buttons (up, down, toTop, toBottom)
autoAdd - default(useAdd) set to false to not automatically add an item
the "change" event will still be dispatched and the orgType will be "add"
the add() method can be used to add user input for instance
autoRemove - default(useRemove) set to false to not automatically add an item
the "change" event will still be dispatched and the orgType will be "remove"
the remove() method can be used to manually remove
autoPosition - default(usePosition) set to false to not automatically position an item
the "change" event will still be dispatched and the orgType will be UP, DOWN, TOP, BOTTOM
the up(), down(), toTop(), toBottom() methods can be used to manually position
addForward - (default true) set to false to add item behind the current item (in list index) when adding
removeForward - (default true) set to false to select the item before the current item (in list index) when deleting
backgroundColor - (default tin) the background color of the buttons
rollBackgroundColor - (default grey) the background color of the button as rolled over
selectedBackgroundColor - (default charcoal) the background color of the button when selected
color - (default white) the text color of a deselected button when not rolled over
rollColor - (default color) the rollover color
selectedColor - (default color) the text color of the selected button
selectedRollColor - (default color) the text color of the rolled over selected button
spacing - (default 2) the distance between the buttons
corner - (default 0) the corner radius of the tabs
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
keyEnabled - (default true) so tab key cycles through tabs, shift tab backwards
gradient - (default null) 0 to 1 (try .3) adds a gradient to the buttons
gloss - (default null) 0 to 1 (try .1) adds a gloss to the buttons
backdropColor - (default dark) the background color of the list window (any CSS color)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(index, item, clone) - manually add item at index - both are optional - index defaults to current index
clone defaults to false - set to true to add a clone of the item - returns object for chaining
up(index) - move item up one index number in list - index defaults to current index - returns object for chaining
down(index) - move item down one index number in list - index defaults to current index - returns object for chaining
toTop(index) - move item to top of list (index 0) - index defaults to current index - returns object for chaining
toBottom(index) - move item bottom of list (index length-1) - index defaults to current index - returns object for chaining
remove(index) - manually remove item at index - index defaults to current index - returns object for chaining
setButtons() - manually rotate buttons to match List direction - automatically done when added to list or list is initially added to organizer
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
All Tab methods
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
list - the list the organizer is operating on
lastIndex - read-only selected index before change event is dispatched
orgIndex - read-only current index of list - same as list.currentIndex
orgItem - read-only selected item of list - same as list.selected
orgType - read-only type of button pressed - "add", "remove", UP, DOWN, TOP, BOTTOM
removedItem - a reference to the item that has been removed when removed button is pressed or remove() is called
group - used when the object is made to add STYLE with the group selector (like a CSS class)
ALSO
see all Tab properties
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "change" event when the buttons are pressed (may be the same button again)
use orgType for what type "add", "remove", UP, DOWN, TOP, BOTTOM
use orgIndex or list.currentIndex for current list index
use orgItem or list.selected for selected item
use removedItem for a removed item
use lastIndex for index before change
ALSO
All Tab events
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Connectors
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
Adds nodes (any DisplayObject - default a Circle) that can be dragged to draw a connector line.
There are three main uses for Connectors:
1. Connecting dots like in coloring books - use linear:true
2. Making hieararchy type drawings - use snaps
3. Connecting objects like boxes together - pass in objects to the points
The num parameter limits the number of lines that can be drawn from a node.
The dropType can be set to require nodes to be dropped on or off other nodes (or the default, any).
There are min and max distances the connections can be made.
These and the other parameters provide a variety of game and puzzle options.
The Line can be set to have start and end heads.
The lineType in the Line can be set to "straight", "corner" or "curve"
Line also accepts points for any arrangement of a connector
but in this version, these have not been used in Connectors.
BASE
A DisplayObject can be used as a base for the connector and have nodes added.
A base can have multiple nodes attached on any of its sides
This approaches diagramming tools like Powerpoint, etc.
but currently, only vertically placed nodes can connect to vertically placed nodes
and horizontally placed nodes can connect to horizontally placed nodes.
DropType single works per node, not per base so use a single node on a base for this.
A base can be a Blob or a Squiggle as well with nodes added to points.
See: https://zimjs.com/cat/connectors.html
PREMADE CONNECTIONS
As of ZIM ZIM 02, Connectors() have a steps property that represents connections made.
Use getSteps(true) when done making connections - this will popup an array of steps.
Copy this array of steps to the steps parameter of the Connector() in the app code.
Connectors will then be made and the additional steps added.
Connectors can also be added to a ZIM TransformManager() so users can easily recreated their connections.
See https://zimjs.com/zim/connectors.html
See https://www.youtube.com/watch?v=ISjW2khGrxoNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
// draws four general connectors that can be connected to one another in a box
// adjust connector nodes after connections are complete
const connectors = new Connectors({linear:true}).center();
connectors.on("complete", ()=>{
connectors.nodes.loop(node=>{
node.radius = 5;
node.color = red;
});
// or hide connectors
// connectors.nodes.alp(0);
S.update();
});
EXAMPLE
// make a grid of connectors and only connect to other nodes
// do not let user delete a node or doubleclick to move a node
const points = [];
const spacing = 60;
loop(10, i=>{
loop(10, j=>{
points.push([i*spacing, j*spacing]);
});
});
const connectors = new Connectors({
points:points,
node:new Rectangle(12,12,purple).centerReg(),
line:new Line({color:purple, thickness:12}),
nodeRollColor:orange,
dropType:"on",
dblclick:false,
deleteNode:false,
max:70
}).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default null) the width of the connnectors container or will grow with added connectors
height - (default null) the height of the connnectors container or will grow with added connectors
points - (default [[0,0], [100,0], [100,100], [0,100]]) an array of point arrays for the connectors
or can be [[x, y, startNode, endNode, startLength, endLength], etc]
x - the x position of the node
y - the y position of the node
startNode - (default true) set to false to not drag from node
endNode - (default true) set to false to not drop on node
startLength - (default null) set line startLength - see Connectors line parameter (for corner or curve lineType)
endLength - (default null) set line endLength - see Connectors line parameter (for corner or curve lineType)
example:
[[0,0,true,false,50], [100,0,false,true], ...]
would allow dragging from the first to the second but not the second to the first
and if the line (see line parameter) is lineType corner or curve the start length would be 50
Another point could have a different startLength to avoid overlapping lines
A convenience object literal can be used as well for any or all points:
[{x:0, y:0, endNode:false, startLength:50}, {x:100, y:0, startNode:false}, ...]
or the first two items in the array can can be a base (that connectors nodes will be added to) and baseInfo as follows:
[[base, baseInfo], [base, baseInfo], [base, baseInfo], etc.]
these can have the startNode, endNode, startLength, endLength as well
and can have the object literal format as follows:
[{base:base, info:baseInfo, etc.}, etc.] rather than the x:x and y:y properties
the baseInfo can be a number of nodes to place around all base sides
or baseInfo can be an array with three different formats:
[all]
[left/right, top/bottom]
[left, right, top, bottom]
These can be numbers greater than 0 for the number of nodes on the side
or 0 for no nodes on the side
or -1 for both corners on the side
or -2 for the first corner on the side
or -3 for the second corner on the side
or can specify a ZIM Blob or Squiggle to place connectors on their points
so: points:blob or points:squiggle
the Blob or Squiggle do not need to be added to the stage
use the getPoints(true) method of the Blob or Squiggle or see https://zimjs.com/paths/
node - (default new Circle(10, grey, grey)) the DisplayObject to use as a node - should be centerReg()
line - (default new zim.Line({thickness:3, color:tin, strokeObj:{caps:"round"}})) the line to use as the connector
ZIM Line has a lineType parameter for "straight", "corner", and "curve" which will affect the connector lines
ZIM Line has a lineOrientation parameter of AUTO, HORIZONTAL or VERTICAL that will affect the connector lines
ZIM LIne has startLength and endLength parameters that work with "corner" and "curve"
these accept ZIM VEE to dynamically set random or a series of values
that can help avoid overlapping lines or
these values can be set individually on the points parameter or on bases directly as properties
which will override any values set on the line provided here in the line parameter
ZIM Line as curveH and curveV settings that will adjust the lines for the "curve" setting
the caps should be set to "round" if drawing with clear or transparent nodes
linear - (default false) lines will only connect to points that are next to one another (in the point order)
this is good for connecting dots
linearWrap - (default true) let the first point connect to the last point in the linear setting
linearOrder - (default false) require the points to be connected in order
num - (default null) set the maximum number of lines that can come from a node
snapH - (default null) snap the nodes to a provided horizontal distance
snapV - (default null) snap the nodes to a provided vertical distance
dropType - (default "any") determines what happens when a node is dropped as follows:
"any" lets the node be dropped anywhere (and may be snapped)
"on" will save the node if dropped on an existing node otherwise it is removed or put back to where it is dragged from
"off" will save the node if not dropped on an existing node otherwise it is removed or put back to where it is dragged from
"single" will save the node if dropped on a node with no existing connections otherwise it is removed or put back to where it is dragged from
note - these only work with the currently dragged node - not other multiple selected nodes
dropArray - (defult null) with "on" or "single" dropType and NOT linear - specify which nodes a node can be connected to
use an array of arrays for each point index [[indexes], [indexes], etc]
eg. [[1,2],[0,2],[3],[0,1]] - if in "on", point 0 can go to 1 or 2, point 1 can go to point 0 or 2, point 2 can only go to 3, etc.
if "single" is set then only one line can be drawn
also see dropIndex and dropArray for each node and the targetNode property
each time a connection is made, a new node is created - these will inherit the dropIndex and dropArray from a targetNode
and if the latestNode's dropArray and its lineArray are the same and the duplicateLine is false then a "blocked" event is dispatched
continuous - (default false) set to true to force nodes to only be made from the last node
all other nodes will have their noMouse() set - also see startIndex - also see linear for doing points in order
startIndex - (default null) set to a point index to force connectors to start at that node
all other nodes will have there noMouse() set - also see continous
duplicateLine - (default true) set to false to not allow multiple lines between the same connectors
deleteNode - (default true) set to false to not allow nodes to be deleted by holding or doubleclicking and delete key
dblclick - (default true) set to false to not allow nodes to be selected by doubleclicking
selected nodes can be moved together
selecting a node selects its children unless the ctrl key is held at which point it will not select children
selected nodes can be deleted with the delete key (or hold to delete)
deleting a node will delete its children
fullMove - (default true) set to false to not automatically drag a node when it is full (if num is set)
min - (default node radius or smallest dimension) the minimum distance from the node's parent a node must move before placing node
max - (default null) the maximum distance from the node's parent a node can be moved to be placed
boundary - (default null) a ZIM Boundary object for the nodes - or a DisplayObject such as the stage (see ZIM Drag)
expand - (default 0 or 10 on mobile) expand the node mousedown area
nodeRollColor - (default node.color.lighten(.2)) the color of the node as rolled over
nodeRollBorderColor - (default node.borderColor) the borderColor of the node as rolled over
nodeSelectedColor - (default white) the selected node color if doubleclicked
nodeSelectedBorderColor - (default node.borderColor) the selected node borderColor if doubleclicked
baseColor - (default node.color) the color of the node connected to a base DisplayObject (see points parameter)
baseBorderColor - (default node.borderColor) the borderColor of the node connected to a base DisplayObject (see points parameter)
baseRollover - (default false) set to true to change all nodes on a base to their roll colors when rolling over the base
rootLock - (default false) do not let the root node (a node in the points array) be draggable or deletable
grandChildren - (default true) do not let there be grandchildren - so there can only be the root nodes and their direct children
dblclickTime - (default .5) time in seconds to capture a double click within (also see ZIM TIME constant)
steps - (default null) pass in an array of [nodeNum, dropX, dropY] arrays to recreate the steps - see getSteps(), setSteps() and steps property
this can be used to recreate a previously made set of connectors and connections
note: the steps may also include a delete flag, and moveX and moveY values and a flag for single select (rather than default children select)
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
addNode(x, y, startNode, endNode, startLength, endLength) - add a node at x and y
cannot add nodes in linear mode - see linear parameter
addNode will not work with the dropArray parameter
x - the x position of the node or provide a base (see Connectors points parameter)
y - the y position of the node or provide base info (see Connectors points parameter)
startNode - (default true) set to false to not drag from node
endNode - (default true) set to false to not drop on node
startLength - (default null) set line startLength - see Connectors line parameter (for corner or curve lineType)
endLength - (default null) set line endLength - see Connectors line parameter (for corner or curve lineType)
removeNode(node) - remove the node (and its children)
removeConnectors() - removes all nodes and connectors except for root nodes which were specified in the points parameter
selectNode(node, children) - select a node and its children unless children parameter is set to false
makeConnection(node, x, y) - add a connection from a node to an x and y position
getSteps(popup) - gets an array of [nodeNum, dropX, dropY] that are automatically recorded each connection. Also see the steps property.
This can then copeied and passed into the steps parameter of Connectors() or the setSteps() method
to recreate recorded connections allowing a set of connectors to be recreated.
note: the steps may also include a delete flag, and moveX and moveY values and a flag for single select (rather than default children select).
setSteps(steps) - add steps to a Connectors() object - or use the steps parameter - also applySteps() for backwards compatibility
steps of [nodeNum, dropX, dropY] are automatically collected when nodes are made and stored in a steps array.
The data for the steps can be collected with getSteps(popup) and shown in a popup window if desired.
Then pass the steps in to the Connectors() step parameter or use setSteps(steps) to recreate the recorded Connectors.
note: the steps may also include a delete flag, and moveX and moveY values and a flag for single select (rather than default children select).
addBase(base, baseInfo) - add nodes to a base DisplayObject - see the points parameter for info about the baseInfo
removeBase(base) - remove the connectors for a base - the base will still need to be removed with removeFrom()
setAvailableIndexes(indexes) - set the provided index or array of indexes to be active
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
latestNode - reference to the latest node while being dragged or and dropped successfully creating a connection
this is set to null if the dragged node is dropped and a connection is not made
see all the properties added to the node objects to get for instance, a creator node
targetNode - reference to a node on which the latestNode was dropped to successfully create a connection
the latestNode will inherit the dropIndex and dropArray from the targetNode
node - the DisplayObject used to make the connector nodes
the node objects also have these added properties:
creator - the node the node was created from (parent in hierarchy) or null if root node
creatorLine - the line going back to the creator or null if root node
creations - an array of nodes made from the node (its children in hiearchy)
before - the node before it in the original points array (or null if first)
after - the node after it in the original points array (or null if last)
nodeColor - remembers the node color in case ZIM VEE is used for color so rolloff knows what color to set
base - the base the node is associated with or null if no base
selected - whether the node is selected or not
orientation - the orientation of the lines from the node
nodeNum - a unique index in order nodes are made
this is used in steps to recreate nodes and connections with the Connectors steps parameter or setSteps(steps) method
dropIndex - get or set the index of the point on which an original node is made
this will get transfered from a targerNode
dropArray - get or set the array of dropIndexes that this node can connect to
this will get transfered from a targerNode
and if the dropArray and the lineArray are the same
and the duplicateLine is false then a "blocked" event is dispatched
lineArray - get an array of indexes to other node connections
this will get transfered to a targetNode
and if the lineArray and dropArray are the same
and the duplicateLine is false then a "blocked" event is dispatched
line - the Line object used to make the connector lines
the line objects also have these added properties:
node - a reference to the node at the start of the line
creatorNode - a reference to the node at the end of the line
nodes - the Container that holds the nodes
lines - the Container that holds the lines
points - a read only array of points of node
steps - an array of [nodeNum, dropX, dropY] arrays that can be used to recreate connections
see also the getSteps(popup) method and the Connectors() steps parameter or setSteps(steps) method to recreate connections
note: the steps may also include a delete flag, and moveX and moveY values.
selectedList - a read-only array of selected nodes
bases - an Array of DisplayObjects used as bases (provided through the points parameter or addBase())
the base objects also have these added properties and methods:
connectors - an array of all connector nodes on the base
connectorMoveEvent - reference to pressmove event on base
connectorUpEvent - reference to pressmove event on base
connectorOverEvent - reference to pressmove event on base
connectorOutEvent - reference to pressmove event on base
setConnectorColors(baseColor, baseBorderColor, nodeRollColor, nodeRollBorderColor) - method to set colors
startNode - set to false to not start a line from this base - see points parameter
endNode - set to false to not end a line on this base - see points parameter
startLength - set a start length for the connector - see points parameter
good to prevent corner and curved lines from overlapping
endLength - set an end Length for the connector - see points parameter
good to prevent corner and curved lines from overlapping
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "connection" event if a new node is made and lastNode property is set to the new node
dispatches a "noconnection" event if the connector is dropped and no new node is made
dispatches a "blocked" event of duplicateLine is false and continuous is true and there are no more connections available
this will happen if the latestNode's dropArray is the same as its linesArray (the order in the array does not matter)
dispatches a "complete" event in linear mode when the connections are complete
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Marquee
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A display for ads and promos using an optional ZIM Indicator with pause button.
The Marquee uses the ZIM Pages class to transition multiple items.
The items can be interactive ZIM objects made ahead of time and passed into the items parameters
Images can also be loaded with the load() method.
See: https://zimjs.com/marquee.html for an example
See: zim Carousel as well for a more simple object with arrows
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const promo1 = new Container(600, 200);
new Rectangle(promo1.width, promo1.height, yellow).addTo(promo1);
new Circle(30, red).center(promo1).drag();
// could be more
// optionally or alternatively, specify a Marquee object
// there can be multiple image properties using end src as key
// just use null as value if no URL
const marqueeData = {"retina.jpg": ["https://zimjs.com/retina.html", "_blank"]};
const marqueePath = "assets/";
// create Marquee
// note the actual width of marquee will be 25+25 more for added margins (optional)
const marquee = new Marquee(600, 200, [promo1])
.center()
.load(marqueeData, marqueePath);
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 300) width of marquee content
final marquee width will have marginLeft and marginRight added to this width
height - (default 100) height of content and marquee
items - default(null) an array of Display Objects - can be interactive
time - default(5) time interval in seconds for changing items (also see ZIM TIME constant)
also see marqueeTime property for each item to individually override the time for viewing
transition - default("slide") the transition between items
options are: "none", "reveal", "slide", "fade", "clear", "black", "white", "fan"
speed - default(.5) speed of transition in seconds (also see ZIM TIME constant)
direction - default(RIGHT) location of next item relative to current item
options are: RIGHT, LEFT, UP, DOWN
marginLeft - default(25) width at left of content for Indicator and Pause button
set to 0 to not show indicator and pause button
marginRight - default(25) width at right of content for Z logo with animated MARQUEE
set to 0 to not show Z logo with animated MARQUEE
marqueeType - (default "dot" or "circle") the Indicator type - also "box" or "square"
borderColor - (default dark) border color - any ZIM or HTML color - set to -1 for no border
borderWidth - (default 1) width of border if borderColor - set to 0 for no border
refresh - (default 30*60 seconds) page refresh to handle browser memory build
mix - (default true) randomize content and then play in that order - different for each page load
note: loaded files will always come after initial marquee items
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
add(obj, url, target) - add a Display Object (obj) - can be interactive content - returns obj for chaining
can provide an overall url and target for url
but often will provide navigation button, etc. as part of interactive content
remove(obj) - remove an object from the marquee - returns obj for chaining
will also call a dispose() method on the obj if there is one
go(page) - transition to specific page (obj) or index - returns obj for chaining
pause(state, immediate) - pause or unpause the Marquee - returns obj for chaining
can be used by interactive code to pause Marquee when interacting
immediate (default false) set to true to make the Marquee go to next item right away when unpausing (no effect when pausing)
load(data, path) - Marquee object for images their optional action url and target: - returns obj for chaining
data in format: {imageSrc:"actionURL", imageSrc:["actionURL", "target"], etc.}
path: optional directory location such as a relative path: "assets/"
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
content - a reference to the ZIM Container that holds the content
pages - a reference to the ZIM Pages object that holds the items
use pages.pages to access an array of pages, etc. - see Pages Class
button - a reference to the pause/play button if there is one
indicator - a reference to the ZIM Indicator if there is one - see Indicator Class
index - the selected index of the Marquee
selected - the selected item of the Marquee
lastSelected - the last selected item of the Marquee
time - get or set the time of the marquee (between changing items)
speed - get the speed of the transition
paused - read only property as to whether the Marquee is paused - see pause() method
interval - a reference to the ZIM interval
left - a reference to the left Container
right - a reference to the right Container if there is one
icon - a reference to the Z icon if there is one
label - a reference to the MARQUEE Label that pops out of the Z if there is one
eg. label.visible = false to not show label popping out
marqueeLoader - a reference to the ZIM loadAssets queue if load() is used
Each item gets a marquee property that points to the ZIM marquee it is in
Each item gets a marqueViews property recording how many times viewed
Each item can have a marqueeTime property set to ms to customize its view time
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "page" event when item starts to change
dispatches a "pagetransitioned" event when item finishes changing
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
Carousel
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
A horizontal display for multiple objects with arrows at sides to animate to previous and next.
This is good for sliding banners, or sliding through a set of icons.
Items will be tiled in a ZIM Tile with one row.
It is expected that the items be the same width and height
but if not, the items will have width set to the most common width and heights aligned vertically to the valign setting.
Thank you Marva for the idea and original code!
See: ZIM Marquee for a more complex alternate format with Indicator
See: https://zimjs.com/zim/carousel.html for an example
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const items = [
new Rectangle(400,80,red).tap(()=>{zog("red");}),
new Rectangle(400,80,green).tap(()=>{zog("green");}),
new Rectangle(400,80,blue).tap(()=>{zgo("https://zimjs.com","_blank");})
];
new Carousel(items, 1).center();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
items - default(seven multicolored rectangles) an array of Display Objects - can be interactive
items will be scaled to the most common width and tiled - see the tile property
a String item will be converted to a new Pic(item)
viewNum - default(3) the number of items to show
time - default(.2) time in seconds to animate between items (also see ZIM TIME constant)
spacing - default(20) the space between the items
backgroundColor - default(clear) the backgroundColor - also see background property
backing - default(null) - an optional backing DisplayObject that goes on top of the backing and under the tile
padding - default(0) - the default for the background outside the tile
paddingH - default(padding) - the horizontal padding to override the padding setting
paddingV - default(padding) - the vertical padding to override the padding setting
arrowLeft - default(new Arrow().rot(180)) - an arrow for going left
arrowRight - default(new Arrow()) - an arrow for going right
arrowGap - default(20) the gap between the arrow and the backing
valign - default(CENTER) the vertical alignment of the tile items
ease - default(quadInOut) the ease of the animation - see ZIM animate() ease parameter for types
swipe - default(true) set to false to not make the tile swipeable - see also the swipe property
remember - default("zimCarousel") set to false to not remember the index when reloading the page
index - default(0 or remembered index) the starting index - see also the index property
this is the index of the first (left) item in view
continuous - default(true) set to false to stop at ends
this will clone the items and use the modulus to keep index numbers correct
if continuous is false and the carousel is cycled then it will bounce back and forth
selectedIndex - same as index, kept in for backwards compatibility in ZIM DUO
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
goRight(time) - go to the right - time defaults to Carousel time parameter but can be customized - returns object for chaining
goLeft(time) - go to the left - time defaults to Carousel time parameter but can be customized - returns object for chaining
cycle(cycleTime, transitionTime, repeat, repeatNum, recycle, rtl) - |ZIM VEE| cycle the carousel from the current index (see also remember)
cycleTime (default 5) in seconds to animate to next item
transitionTime (default 1) in seconds to animate between items - overrides Carousel time setting
often a faster Carousel time is desired for pressing arrows or swiping
but a slower transitionTime when cycling
repeat (default true) continue past ends if carousel continuous is set
or go back and forth from start to end if continuous is not set
set to false to just go one once
repeatNum (default 0) set to a number greater than 0 to limit repeats or bounces - returns object for chaining
for bounce, use .5 for partial cycle for example, 1.5 will go forth then back then forth
recycle (default cycleTime*2) time in seconds to restart cycle if cleared due to arrows or swipes
set to false or -1 to not restart the cycle
rtl (default DIR) if true will stop going back to 0 index if no repeat
cycleClear() - stops the cycle
disableArrows() - turn arrows off - returns object for chaining
enableArrows() - turn arrows on - returns object for chaining
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
index - get or set the first index (left) of the viewable area
items - reference to the original array of items
tile - reference to the single-row tile that holds the items
viewNum - get the number of items viewable
itemWidth - get the calculated item width
itemHeight - get the calculated maximum height
spacing - get the spacing between the items
arrowLeft - reference to the left arrow
arrowRight - reference to the right arrow
swipe - get or set whether the tile can be swiped
repeatTotal - the number of repeats or bounce cycles
swipeObj - reference to the ZIM Swipe object
cycleInterval - reference to the cycle interval
recycleEvent - reference to the recycle event
recycleWait - reference to the recycle timeout
background - reference to the background rectangle
backing - reference to a provided backing
continuous - get whether the carousel is continuous
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
dispatches a "page" event when starting an animation
dispatches a "goleft" and a "goright" event when going left or right - just after the page event
dispatches a "transitioned" event when item finishes changing
dispatches a "bounced" event on each bounce
dispatches a "bouncedone" event if the cycle bounceNum is set and the bounce is done
dispatches a "cyclecleared" event if the cycle is set and stops due to arrow press or swipe
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤
Loader
zim class - extends a zim.Button which extends a zim.Container
DESCRIPTION
Loader lets you upload images, text or JSON. These are available on the loaded event function.
Loader uses the HTML input type=file tag and overlays this with a createjs DOMElement.
Loader is a Button so can be displayed for the user to click on.
It defaults to a dashed line region as you can also drag and drop files to the loader.
You can also save an image using the save() method to a new browser window for the user to save
NOTE
due to the HTML tag being overlayed, the loader.resize() must be called if it is moved
(This is called automatically when the stage is resized)
NOTE
if the loader is placed in a container and the container is removed or added again
the loader must be manually removed or added again with loader.removeFrom() or loader.addTo().
This is so ZIM does not have to keep track of HTML tags each time a container is added or removed.
NOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const loader = new Loader({
label:"UPLOAD PIC OR DROP PICS HERE",
width:700,
height:400,
corner:50
}).center();
loader.on("loaded", e=>{
loop(e.bitmaps, bitmap=>{
bitmap.centerReg().drag();
});
loader.removeFrom();
S.update();
});
// and to later save for instance in a button event:
saveButton.on("click") {
loader.save(stage); // or some other container... can specify crop bounds too
}
EXAMPLE
// loading a JSON file:
const loader = new Loader({
type:"JSON",
label:"UPLOAD JSON",
width:700,
height:400,
corner:50
}).center();
// choose a test.json file with the following in it:
// {"test":"testing"}
loader.on("loaded", e=>{
zog(e.json.test); // "testing"
loader.removeFrom();
S.update();
});
EXAMPLE
// save a json file
const obj = {a:[1,2,3], b:"hello"};
new Loader().save({content:obj, type:"json"}); // save a json file with obj
EXAMPLE
// save a text file
const textInput = new TextInput().center();
new Button({label:"SUBMIT", wait:"SAVED"}).center().mov(0,100).tap(()=>{
new Loader().save({content:textInput.text, filename:"answer.txt", type:"text"});
});
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 250) the width of the button
height - (default 70) the height of the button
label - (default "UPLOAD PIC") ZIM Label or plain text
type - (default "image") set to "text" to receive text or "JSON" to receive a parsed JSON file and "other" for others like MP3
backgroundColor - (default "rgba(0,0,0,.05)") background color of button (any CSS color)
rollBackgroundColor - (default "rgba(0,0,0,.1)") rollover color of button backbground
color - (default "rgba(0,0,0,.5)") text color of button (any CSS color)
rollColor - (default color) rollover text color of button
borderColor - (default rgba(0,0,0,.3)) the color of the border
borderWidth - (default 1) thickness of the border
corner - (default 0) the round of the corner (set to 0 for no corner)
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default "rgba(0,0,0,.3)") set to -1 for no shadow
shadowBlur - (default 14) how blurred the shadow is if the shadow is set
hitPadding - (default 0) adds extra hit area to the button (good for mobile)
gradient - (default 0) 0 to 1 (try .3) adds a gradient to the button
gloss - (default 0) 0 to 1 (try .1) adds a gloss to the button
backing - (default null) a Display object for the backing of the button (eg. Shape, Bitmap, Container, Sprite)
see ZIM Pizzazz module for a fun set of Button Shapes like Boomerangs, Ovals, Lightning Bolts, etc.
https://zimjs.com/bits/view/pizzazz.html
rollBacking - (default null) a Display object for the backing of the rolled-on button
rollPersist - (default false) set to true to keep rollover state when button is pressed even if rolling off
icon - (default false) set to display object to add icon at the center of the button and remove label
https://zimjs.com/bits/view/icons.html
rollIcon - (default false) set to display object to show icon on rollover
toggle - (default null) set to string to toggle with label or display object to toggle with icon or if no icon, the backing
rollToggle - (default null) set to display object to toggle with rollIcon or rollBacking if no icon
there is no rollToggle for a label - that is handled by rollColor on the label
toggleEvent - (default mousedown for mobile and click for not mobile) what event causes the toggle
dashed - (default true) set to false to turn off the dashed for the border
frame - (default the zdf) a reference to the Frame (to scale and position the HTML tag)
multiple - (default true) set to false to let user only upload one file rather than multiple files (with shift or ctrl)
accept - (default null) set to extension / MIME-type to limit types of files the upload dialog will suggest
here are some examples:
"image/*"
"image/jpeg, image/png"
".png, .jpeg, .jpg, .gif"
"image/jpeg, .jpeg, .jpg"
".txt, .json, application/json"
"audio/mpeg, .mp3"
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
resize() - call the resize event if the scale or position of the Loader is changed
this will sync the location of the HTML input tag
resize() is only needed if the scale or x, y of the Loader (or its container) is changed
it is not needed for general window resizing - the Loader handles this
Note: if the Frame itself changes location in the HTML document, call a F.update()
this will then dispatch an update event to the Loader and it will resize()
this is not needed if resizing the window or scrolling - see Frame update() method docs
save(content, filename, x, y, width, height, cached, cachedBounds, type, data, quality) - save a picture or text (supports ZIM DUO)
content - the Display object to be saved such as a Container, Bitmap, etc.
or text (or Label, TextInput, TextArea) or JSON or object for JSON
if text or json, then x, y, width, height, cached, cachedBounds, data, and quality are ignored
filename - (default random) - the text name of the file (with or without extension - also see type)
x, y, width, height - the cropping bounds on that object otherwise defaults to 0,0,W,H
cached - (default false) set to true if the object is currently already cached
cachedBounds - if you are saving a different bounds than was previously cached
setting the bounds here (createjs.Rectangle) will restore the cache to the previous bounds
type - (default "png") set to "jpeg" for jpeg or "txt", "text" or "json"
json will convert the content to JSON if it is not already in JSON format
data - (default false) set to true to save as base64 data
otherwise save returns the object for chaining
quality - (default .92) a number between 0 an 1 representing the quality of the saved image (jpeg)
note, this parameter may be moved to before data in the next version of ZIM
Button methods:
setBacking(type, newBacking) - dynamically set any type of backing for button (if null removes backing for that type)
Backing types are: "backing", "rollBacking", "toggleBacking", "rollToggleBacking", "waitBacking", "rollWaitBacking"
note - all backing will have a pattern property if a pattern is set as a backing
setIcon(type, newIcon) - dynamically set any type of icon for button (if null removes icon for that type)
Icon types are: "icon", "rollIcon", "toggleIcon", "rollToggleIcon", "waitIcon", "rollWaitIcon"
toggle(state) - forces a toggle of label if toggle param is string, else toggles icon if icon is set or otherwise toggles backing
state defaults to null so just toggles
pass in true to go to the toggled state and false to go to the original state
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
tag - the HTML input tag of type file - used for uploading
frame - get or set the frame - set this if changing frames
Button properties:
text - references the text property of the Label object of the button
label - gives access to the label
backgroundColor - get or set non-rolled on backing color (if no backing specified)
rollBackgroundColor - get or set rolled on backing color
color - get or set non-rolled on text color (if no icon specified)
rollColor - get or set rolled on text color
backing - references the backing of the button
rollBacking - references the rollBacking (if set)
icon - references the icon of the button (if set)
rollIcon - references the rollIcon (if set)
toggleObj - references the toggle object (string or display object if set)
rollToggle - references the rollToggle (if set)
toggled - true if button is in toggled state, false if button is in original state
enabled - default is true - set to false to disable
rollPersist - default is false - set to true to keep rollover state when button is pressed even if rolling off
focus - get or set the focus property of the Button used for tabOrder
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
ACTIONEVENT
This component is affected by the general ACTIONEVENT setting
The default is "mousedown" - if set to something else the component will act on click (press)
EVENTS
loaded - is dispatched when the files(s) are uploaded - the event object comes with the following properties:
FOR IMAGES (see types array)
e.bitmaps - an array of Bitmap objects of the loaded images
e.bitmap - the first Bitmap to be created from the loaded images
e.lastBitmap - the last Bitmap to be created from the loaded images
e.total - the total Bitmap objects to be created from the loaded images
FOR TEXT (see types array)
e.texts - an array of String objects of the loaded text files
e.text - the first text loaded
e.lastText - the last text loaded
e.total - the total number of texts loaded
FOR JSON (see types array)
e.jsons - an array of JSON objects of the loaded JSON files
e.json - the first JSON object loaded
e.lastJSON - the last JSON object loaded
e.total - the total number of JSON files loaded
FOR OTHER (see types array)
e.others - an array of other objects of loaded files
e.other - the first other object loaded
e.lastOther - the last other object loaded
e.total - the total number of other files loaded
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤VIDS
TextArea
zim class - extends a zim.Container which extends a createjs.Container
DESCRIPTION
TextArea creates an input text field by overlaying an HTML TextArea.
The TextArea is then overlayed with the createjs DOMElement
and scaled and positioned with ZIM code. This can also be used if selectable text is required
Access to the HTML tag is provided with the TextArea tag property.
So CSS Styles can be applied to the HTML tag as with any HTML textarea tag
The TextArea comes with a ZIM Rectangle in behind that you can adjust with parameters
or remove completely if you so desire using the TextArea background property
ie. myTextArea.background.alpha=0; or myTextArea.removeChild(myTextArea.background)
NOTE
due to the HTML tag being overlayed, the TextArea.resize() must be called if it is moved
(This is called automatically when the stage is resized)
It also means that a TextArea in a Window or List is probably not a good thing.
Consider using Label and then toggling a TextArea on mouseover and mouseout.
See https://zimjs.com/snips for an older discontinued example.
NOTE
if the TextArea is placed in a container and the container is removed or added again
the textArea must be manually removed or added again with textArea.removeFrom() or textArea.addTo().
This is so ZIM does not have to keep track of HTML tags each time a container is added or removed.
When using TextArea in a Pane or in Pages this will be automatically handled
only if the TextArea is directly in the Pane or the page (not nested in further Containers)
NOTE
rotation and skewing of TextArea is not supported - although might work with custom CSS transformations
NOTE
because of these limitations, consider the TextEditor as a solution.
The TextEditor allows you to use a Label which is a proper part of the Canvas
and then change the label with a pop-up editor that includes a TextArea.
SEE: https://zimjs.com/cat/texteditor.htmlNOTE
as of ZIM 5.5.0 the zim namespace is no longer required (unless zns is set to true before running zim)
EXAMPLE
const textArea = new TextArea(300, 200).center();
const label = new Label({text:""}).pos(20,20);
textArea.on("input", ()=>{
label.text = textArea.text;
S.update();
});
// to set scrollBars on TextArea use CSS on the TextArea tag property:
textArea.tag.style.overflow = "auto"; // etc.
// if manually scaled or positioned (or container is scaled or positioned)
// then the TextArea must be resized with the resize method
textArea.sca(.5).mov(200);
textArea.resize();
PARAMETERS
** supports DUO - parameters or single object with properties below
** supports OCT - parameter defaults can be set with STYLE control (like CSS)
width - (default 250) the width of the TextArea backing (the textarea field will be that less the padding*2)
height - (default 70) the height of the TextArea backing (the textarea field will be that less the padding*2)
Note: to set scrollBars use CSS: textArea.tag.style.overflow = "auto";
placeholder - (default null) the HTML placeholder for the TextArea
text - (default null) the text of the TextArea - see also the text property
size - (default 20) a Number for the font-size of the TextArea (do not use px on the end)
to change the font, use CSS on the tag property: textArea.tag.style.fontFamily = "courier";
padding - (default 5) the pixels between the backing border and the HTML textarea
color - (default granite) text color (any CSS color)
backgroundColor - (default "rgba(256,256,256,.1)") background color of box
borderColor - (default rgba(0,0,0,.1)) the color of the border
borderWidth - (default 1) thickness of the border
corner - (default 0) the round of the corner (set to 0 for no corner)
can also be an array of [topLeft, topRight, bottomRight, bottomLeft]
shadowColor - (default null) the shadow color (css color) of a drop shadow
shadowBlur - (default null) pixels of how blurred the shadow is if the shadow is set - eg. 10
dashed - (default true) set to false to turn off the dashed for the border
id - (default null) a string id for the HTML textarea tag for CSS styling, etc.
placeholder - (default null) a string that is used for the HTML textarea tag placeholder parameter
readOnly - (default false) set to true to make TextArea read only (still selectable)
spellCheck - (default true) set to false to turn Browser spell check off
password - (default false) set to true to turn the field into a password field - single line only (uses input field type=password and not TextArea)
inputType - (default false) set to "text" to show a text input (one line) - or try other HTML input types - "email", "number", etc.
the various types of HTML inputs are not really tested - would suggest using Tag() instead for these (or preferably ZIM components)
wrap - (default true) set to false to stop the textarea from wrapping (css white-space:pre)
maxLength - (default null) set to a number to limit the number of characters in the textarea
frame - (default the zdf) a reference to the Frame (to scale and position the HTML tag)
expand - (default 20) hit area around background to count as a press on TextArea - handy for dragging as HTML tag area will override mouse on canvas
keyboardShift - (default false) set to true to lift stage at least 1/4 height or up to textArea y/2 to raise textArea above keyboard
style - (default true) set to false to ignore styles set with the STYLE - will receive original parameter defaults
group - (default null) set to String (or comma delimited String) so STYLE can set default styles to the group(s) (like a CSS class)
inherit - (default null) used internally but can receive an {} of styles directly
METHODS
setFocus(type) - sets the focus of the TextArea tag (thanks Armin for the prompting)
type is a Boolean that defaults to true - set to false to make the TextArea blur (loose focus)
might need timeout 100ms before setting
see also focus property
resize() - call the resize method if the scale or position of the TextArea is changed
this will sync the location of the HTML textarea tag
resize() is only needed if the scale or x, y of the TextArea (or its container) is changed
it is not needed for general window resizing - the TextArea handles this
Note: if the Frame itself changes location in the HTML document, call a F.update()
this will then dispatch an update event to the TextArea and it will resize()
this is not needed if resizing the window or scrolling - see Frame update() method docs
hasProp(property as String) - returns true if property exists on object else returns false
clone() - makes a copy with properties such as x, y, etc. also copied
dispose() - removes from parent, removes event listeners - must still set outside references to null for garbage collection
ALSO
ZIM 4TH adds all the methods listed under Container (see above), such as:
drag(), hitTestRect(), animate(), sca(), reg(), mov(), center(), centerReg(),
addTo(), removeFrom(), loop(), outline(), place(), pos(), alp(), rot(), setMask(), etc.
ALSO
see the CreateJS Easel Docs for Container methods, such as:
on(), off(), getBounds(), setBounds(), cache(), uncache(), updateCache(), dispatchEvent(),
addChild(), removeChild(), addChildAt(), getChildAt(), contains(), removeAllChildren(), etc.
PROPERTIES
type - holds the class name as a String
value - get or set the text content of the TextArea
text - get or set the text value
focus - get or set if the TextArea tag has focus or use setFocus() to set (might need timeout 100ms before setting)
readOnly - set to true to not be able to edit or to false to be able to edit (always can select)
maxLength - get or set the maximum number of characters typed - will not truncate existing characters until typed
tag - the HTML textarea tag - just a regular HMTL form tag which can be styled
background - access to the Rectangle() used for the background
you can remove this with yourTextArea.background.removeFrom(yourTextArea);
or adjust it dynamically with any of the Rectangle properties like color
blendMode - how the object blends with what is underneath - such as "difference", "multiply", etc. same as CreateJS compositeOperation
keyFocus - get or set the keyboard focus on the component - see also zim.KEYFOCUS
will be set to true if this component is the first made or component is the last to be used
frame - get or set the frame - set this if changing frames
ALSO
see ZIM Container for properties such as:
width, height, widthOnly, heightOnly, draggable, level, depth, group
blendMode, hue, saturation, brightness, contrast, etc.
ALSO
see the CreateJS Easel Docs for Container properties, such as:
x, y, rotation, scaleX, scaleY, regX, regY, skewX, skewY,
alpha, cursor, shadow, name, mouseChildren, mouseEnabled, parent, numChildren, etc.
EVENTS
focus, blur are dispatched when the text area gains and loses focus
input is dispatched when the text area is typed or pasted into
capture the event object data property to see what letter is typed
change is dispatched when the text area is different after losing focus
These are just the html events passed on through - note the difference between input and change!
ALSO
see the CreateJS Easel Docs for Container events such as:
added, click, dblclick, mousedown, mouseout, mouseover, pressdown (ZIM), pressmove, pressup, removed, rollout, rollover
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
cache
zim DisplayObject method overrides CreateJS cache() method with more flexible parameters
https://createjs.com/docs/easeljs/classes/Container.html#method_cacheDESCRIPTION
Turns the object into a bitmap which can be rendered more efficiently, especially on mobile.
Caching may blur the object slightly, most noticable when caching a Label.
Every stage update must re-render objects on the stage.
This can be processor intensive for lots of vectors - such as Labels and Shapes.
Generally, we can build without caching but if better performance is needed, then caching may help.
A cached object can be transformed (scale, rotation, position, skew, alpha)
but if the object inside changes, for instance if the text changes, then updateCache() will need to be called.
Constantly calling updateCache() for instance, an animated blob, will not help performance.
A handy trick is to cache an object before animating and uncaching it after animating
this can improve animation performance and the slight blur of the object is not noticed during animation.
ALSO SEE: updateCache() and uncache()
EXAMPLE
const circle = new Circle(50, red).cache().center();
timeout(1, ()=>{
circle.alpha = .5; // cache does not have to be updated to see alpha change
S.update();
});
timeout(2, ()=>{
circle.color = blue;
circle.updateCache(); // cache must be updated to see color change
S.update();
});
EXAMPLE
// cache text as it is animated
new Label("Cached Text")
.cache() // cache the text so animation is smoother
.alp(0)
.center()
.animate({
props:{alpha:1},
time:2,
call:target=>{
target.uncache(); // uncache the label so it is crisper looking
}
});
PARAMETERS supports DUO - parameters or single object with properties below
** cache dimensions will be set to the bounds of the object if the first two or four parameters are not provided
width||x - (default getBounds().x) the width of the chache - or the x if first four parameters are provided
height||y - (default getBounds().y) the height of the chache - or the y if first four parameters are provided
width - (default getBounds().width) the width of the chache - or null if first two parameters are provided
height - (default getBounds().height) the height of the chache - or null if first two parameters are provided
scale - (default 1) set to 2 to cache with twice the fidelity if later scaling up
options - (default null) additional parameters for cache logic - see CreateJS somewhere for details
also added adjustBounds property for options - set to true to set new bounds and registration point
on cached objects with x,y,width,height different than the original
this appears to NOT be the default with createjs cache() which keeps the original registration point and bounds
automatically fixing this changes lots of things so use the adjustBounds option when needed
for instance when caching parts of a container and requiring hit tests or the part to be draggable, etc.
margin - (default 0) add or subtract a margin from the bounds
eg. margin:10 will make the cache size 10 pixels more on all sides
this can be handy when caching objects with borders - that go half outside the natural bounds
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
const circle = new Circle(50, red).cache().center();
timeout(1, ()=>{
circle.alpha = .5; // cache does not have to be updated to see alpha change
S.update();
});
timeout(2, ()=>{
circle.color = blue;
circle.updateCache(); // cache must be updated to see color change
S.update();
});
PARAMETERS
blendMode - (default null) a blendMode (compositeOperation) see ble()
if a blendMode is provided the previous cache is not deleted as the new cache is drawn
RETURNS null
CLOSE ▲PAGE ▤CODE ▤
// cache text as it is animated then uncache
new Label("Cached Text")
.cache() // cache the text so animation is smoother
.alp(0)
.center()
.animate({
props:{alpha:1},
time:2,
call:target=>{
target.uncache(); // uncache the label so it is crisper looking
}
});
on
CreateJS method
https://createjs.com/docs/easeljs/classes/Container.html#method_onDESCRIPTION
Captures events. Similar to addEventListener() in raw JavaScript
but is shorter to write and has a few extra features.
Generally, events are when interactivity occurs or ZIM has a message.
Here are some types:
"click", "dblclick", "mousedown/pressdown", "pressmove", "pressup",
"mousemove", "stagemousemove", "mouseover", "mouseout"
"ready", "complete", "change", "keydown", "keyup"
The events available for ZIM Objects are listed at the bottom of their Doc entry.
Events can also be turned off in a couple ways - see the examples.
To turn the event off the return value of the on() method is used
so DO NOT CHAIN THE ON METHOD
ALSO SEE: off() and tap(), change(), movement(), hov(), hold()
EXAMPLE
// BASIC EVENT
const button = new Button().center();
// the type of event as a string and the function to call
// here we use an arrow function
button.on("click", ()=>{
zgo("https://zimjs.com", "_blank");
});
// alternatively, using an anonymous function
button.on("click", function() {
zgo("https://zimjs.com", "_blank");
});
// alternatively, using a named function
// do not put () after the function name
// that would call the function right away which is not desired
// we want to tell the on() method which function to run when the event happens
button.on("click", doClick);
function doClick() {
zgo("https://zimjs.com", "_blank");
}
EXAMPLE
// EVENT OBJECT
const tile = new Tile(new Rectangle(), 5, 5, 2, 2).center();
tile.on("mousedown", e=>{ // collect the event object in parameter e
// e.target is the object that caused the event (one of the rectangles)
e.target.alpha = 0;
// e.currentTarget is the object on which the event is placed (the tile)
e.target.mov(5);
// do not forget to update stage in events if needed!
S.update();
});
EXAMPLE
// REMOVING EVENT
let keyEvent = F.on("keydown", e=>{
zog(e.keyCode); // will tell code for key pressed
// etc.
});
timeout(2, ()=>{ // time in seconds as of ZIM Cat
// remove the keyEvent
F.off("keydown", keyEvent);
});
// RE-ADDING EVENT
timeout(4, ()=>{
// add the keyEvent back again
// note - the event must be re-assigned to use again
// this leads to a tricky bug if not careful!
keyEvent = F.on("keydown", keyEvent);
});
timeout(6, ()=>{
// remove the keyEvent again
// this only works if we re-assigned the latest event to keyEvent
// which is why we used let rather than const
F.off("keydown", keyEvent);
});
EXAMPLE
// ONE EVENT CALL
// call this function only once when mousing over the stage
// note: "mousemove" would only trigger if moving over an object on the stage
S.on("stagemousemove", ()=>{
pauseAnimate(false); // unpause all animations
}, null, true); // this true means remove the event after calling it once
// REMOVE METHOD
// a remove() method is available on the event object
const circle = new Circle().center();
circle.on("mouseover", e=>{
circle.alpha -= .1;
if (circle.alpha <= .5) e.remove();
S.update();
});
PARAMETERS
type - the type of event as a string - this depends on the object on which the event is being placed
here are some common events - see the EVENTS section of the specific object for more
"click", "dblclick", "mousedown/pressdown", "pressmove", "pressup",
"mousemove", "stagemousemove", "mouseover", "mouseout"
"ready", "complete", "change", "keydown", "keyup"
listener - the function to call when the event happens
this is often an arrow function or an anonymous function but can be a named function
the function will receive an event object as its parameter often collected as e
see https://createjs.com/docs/easeljs/classes/MouseEvent.html for properties, etc.
common event object properties are:
target (what caused the event),
currentTarget (what the event was placed on)
keyCode (for key events)
often used as e.target, e.currentTarget, e.keyCode
scope - (optional) the scope to execute the listener in.
Defaults to the dispatcher/currentTarget for function listeners,
and to the listener itself for object listeners (ie. using handleEvent).
once - (default false) set to true to remove the listener after the first event call
data - (default null) arbitrary data that will be included as the second parameter when the listener is called.
useCapture - (default false) for events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase
RETURNS a reference to use as the second parameter of the off() method to turn the event off (SO DO NOT CHAIN THE ON METHOD)
CLOSE ▲PAGE ▤CODE ▤
// REMOVING EVENT
let keyEvent = F.on("keydown", e=>{
zog(e.keyCode); // will tell code for key pressed
// etc.
});
timeout(2, ()=>{ // time in seconds as of ZIM Cat
// remove the keyEvent
F.off("keydown", keyEvent);
});
// RE-ADDING EVENT
timeout(4, ()=>{
// add the keyEvent back again
// note - the event must be re-assigned to use again
// this leads to a tricky bug if not careful!
keyEvent = F.on("keydown", keyEvent);
});
timeout(6, ()=>{
// remove the keyEvent again
// this only works if we re-assigned the latest event to keyEvent
// which is why we used let rather than const
F.off("keydown", keyEvent);
});
PARAMETERS
type - the string type of the event used in on()
listener - the listener function or object used in on()
useCapture - (default false) the setting for the capture or bubbling/target phase used in on()
RETURNS null
CLOSE ▲PAGE ▤CODE ▤
getBounds
CreateJS method
https://createjs.com/docs/easeljs/classes/Container.html#method_getBoundsDESCRIPTION
Gets bounds data for a Display Object (with bounds set).
This will have x, y, width and height properties.
Imagine the bounds as an invisible rectangle around the object.
The bounds are what dictate the width and height of an object (along with scale).
The bounds will affect how an object is positioned with pos().
The bounds also may affect certain types of hitTests.
Most ZIM DisplayObjects have their bounds set automatically.
Shape() however does not have its bounds set automatically.
ALSO SEE: setBounds()
EXAMPLE
const rect = new Rectangle(100, 100, blue).center();
zog(rect.getBounds()); // {x:0, y:0, width:100, height:100}
const circle = new Circle(100, red).center(); // 100 is the radius
zog(circle.getBounds()); // {x:-100,y:-100,width:200,height:200}
// note that a Circle has its origin (0,0) in the middle
// so half the bounds goes to the left and above
// and the width and height are twice the radius
// Also note that the registration point is completely independent from the bounds
// and independent from the origin. See https://codepen.io/zimjs/pen/qBEjYZV
setBounds
zim DisplayObject method overrides CreateJS setBounds() method with more flexible parameters
https://createjs.com/docs/easeljs/classes/Container.html#method_setBoundsDESCRIPTION
Sets bounds for a Display Object.
Imagine the bounds as an invisible rectangle around the object.
The bounds are what dictate the width and height of an object (along with scale).
The bounds will affect how an object is positioned with pos().
The bounds also may affect certain types of hitTests.
Most ZIM DisplayObjects have their bounds set automatically.
Shape() however does not have its bounds set automatically.
The setBounds() method will override any automatic bounds.
ALSO SEE: getBounds()
EXAMPLE
new Shape().f(red).dr(0,0,100,100).setBounds(100,100).center();
// without bounds set on the shape, it would not center properly
EXAMPLE
// Containers have two options for how bounds are determined
// 1. the size can be passed in to start in which case these bounds will remain unchanged
// 2. or no size can be passed in which means the bounds will grow to the contents
// setting bounds to null will convert a type 1 container into a type 2 container
const holder = new Container(100,100).center();
new Rectangle(200,200).addTo(holder);
// currently the bounds are {x:0,y:0,width:100,height:100}
holder.setBounds(null);
// now the bounds are {x:0,y:0,width:200,height:200}
new Rectangle(300,300).addTo(holder);
// now the bounds are {x:0,y:0,width:300,height:300}
holder.setBounds(100,100);
// now the bounds are back to {x:0,y:0,width:100,height:100}
// this example just demonstrates it would not be very practical
PARAMETERS
width||x||Boundary - (default null) the width of the bounds - or the x if four parameters are provided
or a ZIM Boundary Object {x,y,width,height} - same as CreateJS Rectangle
height||y - (default width) the height of the bounds - or the y if four parameters are provided
width - (default null) the width of the bounds - or null if only the first two parameters are provided
height - (default null) the height of the bounds - or null if only the first two parameters are provided
RETURNS the object for chaining
CLOSE ▲PAGE ▤CODE ▤
localToGlobal
zim DisplayObject method overrides CreateJS localToGlobal() method with adjustment for scaled stage due to retina pixel density
https://createjs.com/docs/easeljs/classes/Container.html#method_localToGlobalDESCRIPTION
Returns a point on the stage for the provided x and y within the object's (container's) coordinate system.
BACKGROUND
Each container has its own x and y coordinate system. The stage is said to be the global coordinate system.
Since containers may be located at different x and y positions and nested inside one another and scaled, rotated or skewed,
finding the matching x and y position within different coordinates can be tricky to calculate.
Traditionally in Interactive Media, three methods have been provided to translate x and y between coordinate systems.
localToGlobal() finds the global x and y of a specified x and y inside the container object
globalToLocal() finds the x and y inside the container object of a specified global x and y
localToLocal() finds the x and y inside an other specified container of a specified x an y inside the container object
SEE: https://zimjs.com/editor/view/Z_N5E7Z
ALSO SEE: globalToLocal() and localToLocal()
EXAMPLE
const holder = new Container(400,400).loc(100,100);
const circle = new Circle.center(holder);
zog(holder.localToGlobal(circle.x, circle.y)); // {x:300, y:300}
// Note: and easier way providing the same result is:
zog(circle.localToGlobal(0,0)); // {x:300, y:300}
PARAMETERS
x - (default null) the x position inside the container
y - (default null) the y position inside the container
RETURNS a Point with x and y properties on the stage (global) that match the provide x and y inside the container
CLOSE ▲PAGE ▤CODE ▤
globalToLocal
zim DisplayObject method overrides CreateJS globalToLocal() method with adjustment for scaled stage due to retina pixel density
https://createjs.com/docs/easeljs/classes/Container.html#method_globalToLocalDESCRIPTION
Returns a point within the object's (container's) coordinate system that matches the provided x and y on the stage (global).
BACKGROUND
Each container has its own x and y coordinate system. The stage is said to be the global coordinate system.
Since containers may be located at different x and y positions and nested inside one another and scaled, rotated or skewed,
finding the matching x and y position within different coordinates can be tricky to calculate.
Traditionally in Interactive Media, three methods have been provided to translate x and y between coordinate systems.
localToGlobal() finds the global x and y of a specified x and y inside the container object
globalToLocal() finds the x and y inside the container object of a specified global x and y
localToLocal() finds the x and y inside an other specified container of a specified x an y inside the container object
SEE: https://zimjs.com/editor/view/Z_N5E7Z
ALSO SEE: localToGlobal() and localToLocal()
EXAMPLE
const rect = new Rectangle(500,500,red).center();
const circle = new Circle(20,purple).center(rect).noMouse(); // noMouse so movement turns off when outside rect
rect.movement(()=>{
circle.loc(rect.globalToLocal(F.mouseX, F.mouseY)); // convert global mouse to x and y point within rect container
S.update();
});
// Note: see Frame cursors property to do this more easily and precisely
PARAMETERS
x - (default null) the x position inside the container
y - (default null) the y position inside the container
RETURNS a Point with x and y properties inside the container that match the provided x and y points on the stage (global)
CLOSE ▲PAGE ▤CODE ▤
localToLocal
zim DisplayObject method overrides CreateJS localToLocal() method with adjustment for scaled stage due to retina pixel density
https://createjs.com/docs/easeljs/classes/Container.html#method_localToLocalDESCRIPTION
Returns a point with x and y positions inside the provided target container's coordinate system
that match the x and y within the object's (container's) coordinate system.
BACKGROUND
Each container has its own x and y coordinate system. The stage is said to be the global coordinate system.
Since containers may be located at different x and y positions and nested inside one another and scaled, rotated or skewed,
finding the matching x and y position within different coordinates can be tricky to calculate.
Traditionally in Interactive Media, three methods have been provided to translate x and y between coordinate systems.
SEE: https://zimjs.com/editor/view/Z_N5E7Z
localToGlobal() finds the global x and y of a specified x and y inside the container object
globalToLocal() finds the x and y inside the container object of a specified global x and y
localToLocal() finds the x and y inside an other specified container of a specified x an y inside the container object
ALSO SEE: globalToLocal() and localToLocal()
EXAMPLE
const wheel = new Circle(300, blue).center().animate({props:{rotation:360}, time:5, loop:true, ease:"linear"});
const level = new Circle(20).loc(0,250,wheel); // will spin around with wheel
const land = new Container(800,800).center();
const player = new Circle(50,purple).center(land).drag(land);
Ticker.add(()=>{
if (player.y < level.localToLocal(0,0,land).y) player.color = red; // if player goes below level
else player.color = purple; // player is above level
});
PARAMETERS
x - (default null) the x position inside the container
y - (default null) the y position inside the container
target - (default null) the target container in which to match the provided x and y positions
RETURNS a Point with x and y properties in the target container that match the provide x and y inside the object container
CLOSE ▲PAGE ▤CODE ▤
clone
zim DisplayObject method overrides CreateJS cache()
https://createjs.com/docs/easeljs/classes/Container.html#method_cloneDESCRIPTION
Makes a copy of the DisplayObject (and children).
The clone() method is particularily handy for making multiple assets from a single asset()
Although new Pic() instead of asset() is automatically cloned to give a new object each new Pic()
ALSO SEE: duplicate() to duplicate custom properties as well
EXAMPLE
const circle = new Circle(100, red).center();
circle2 = circle.clone().pos(100,100,RIGHT,BOTTOM); // make a copy and position at bottom right
EXAMPLE
asset("pic.jpg").center();
asset("pic.jpg").pos(100,100,RIGHT,BOTTOM); // will just move the existing asset to the corner
asset("pic.jpg").clone().pos(100,100,RIGHT,TOP); // will add a copy of the asset at the top
new Pic("pic.jpg").pos(0,100,CENTER); // no need to clone() a new Pic()
PARAMETERS
exact (default false) ZIM VEE (Pick) values are active in clones unless exact is set to true
For instance, if a Container holds a new Circle(20,[blue,green])
then its clone might be blue or green
If exact is set to true then the clone will be whatever color was picked for the original circle
RETURNS the object for chaining
CLOSE ▲PAGE ▤CODE ▤
dispose
zim DisplayObject method
DESCRIPTION
Deletes the DisplayObject from memory.
This means it removes event listeners, stops animations, drags, gestures, transforms, etc.
The references to the DisplayObject must still be set to null for proper garbage collection.
Objects that have references to them may still be saved in memory
and this can lead to memory leaks if many objects are being made.
The average DisplayObject added to the stage and removed does not really need to be disposed()
Only when hundreds or thousands of objects are being made will there be need for dispose()
SEE: https://www.youtube.com/watch?v=aTnNicsLP3A // on memory management
EXAMPLE
const tile = new Tile(new Pic("pic.jpg"), 100, 100).center();
const tilesArray = [tile]; // if we had an array of such tiles
const tilesObject = {fave:tile}; // if we had a reference in an object literal
timeout(10, ()=>{
tile.dispose(); // will recursively dispose all children in Tile (the Bitmaps)
tile = null; // remove the reference to tile
tilesArray[0] = null; // set the array reference to null
delete tilesObject.fave; // delete the property in the object literal
S.update();
});
PARAMETERS
disposing - (default null) pass in true to indicate already started dispose if calling dispose() on the super class from a custom class
otherwise infinite looping can occur (used internally by ZIM)
RETURNS the object for chaining
CLOSE ▲PAGE ▤CODE ▤
--------------ADDING AND REMOVING
EXPAND ▼ obj.addTo(container, index, still)
addTo
zim DisplayObject method
DESCRIPTION
A wrapper function for addChild() / addChildAt() to add the obj to the container.
This allows us to chain more effectively:
var circle = new Circle().addTo(stage).drag();
Also, ZIM has obj.center(container) and obj.centerReg(container) functions
where the obj comes first followed by the container.
So it is a pain to flip things and use container.addChild(obj)
Now, we can use obj.addTo(container) and the object we are adding comes first.
The index parameter is similar to an addChildAt()
We can also use obj.removeFrom() to automatically remove from the container
EXAMPLE
const circle = new Circle(50, red);
circle.addTo(stage); // or just circle.addTo(); // for the default frame's stage
// with chaining - and dragging:
var circle = new Circle(50, red).addTo().drag();
const rect = new Rectangle(100, 100, blue);
rect.addTo(stage, 0); // place on bottom
EXAMPLE
// Changing Coordinates
// An object may appear to change positions
// when you add from one container to another (the stage is a container too).
// This happens because the x and y origin inside the containers may be at different places
// yet the x and y property of the object remains unchanged.
// The "still" parameter converts between the coordinates and updates the x and y
// so that the object does not appear to jump - this defaults to true
const container = new Container().pos(100,100);
const rectangle = new Rectangle(200, 200, yellow).addTo(container);
// we want to drag the container and the circle
// but when the circle is in the container we want to drag the circle independently
// this leads to a tricky situation that can be solved as follows:
rectangle.on("mousedown", function() {container.drag({currentTarget:true});});
rectangle.on("pressup", function() {container.noDrag();});
const circle = new Circle(50, blue).center().drag();
// check to see if the circle is over the container and if so then add the circle
// try settin the third parameter to false to see what would normally happen
circle.on("pressup", ()=>{
if (rectangle.hitTestReg(circle)) { // do not hitTest the container!
circle.addTo(container); // keep position with default true as third parameter
} else {
circle.addTo(stage);
}
S.update();
});
PARAMETERS supports DUO - parameters or single object with properties below
container - (default first frame's stage) the container to add to
index - (default null) if provided will addChildAt the object at the index (0 being bottom)
still - (default true or false if no parent) makes object not move when added from one coordinate space to another
this also may change the objects x and y properties - set to false not to do this
uses localToLocal() to accomplish this
the still parameter is ignored if object currently does not have a parent
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
removeFrom
zim DisplayObject method
DESCRIPTION
A chainable wrapper function for removeChild() that removes the obj from the container
Matches obj.addTo(container)
We have obj.removeFrom(container)
NOTE
do not need to specify container as removeFrom()
will remove the object from its parent.
EXAMPLE
const circle = new Circle(50, red);
circle.addTo(); // adds to stage
// later
circle.removeFrom(); // same as circle.removeFrom(stage)
PARAMETERS
container - (default the object's parent) the container to remove the object from
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS
added
zim DisplayObject method
DESCRIPTION
Calls callback function when object is added to the stage
CreateJS has an "added" event that triggers when an object is added to another container
but this container may not be on the stage.
added polls several times quickly and then every 100ms to see if the object has a stage property
Once it does then it calls the callback and removes the interval
EXAMPLE
const circle = new Circle(50, red);
circle.added(()=>{zog("has stage");});
PARAMETERS
callback - the function to call when added - will call right away if object is already added
call will receive a reference to the stage and the object as parameters
** these two parameters are depricated as added no longer uses an interval as of ZIM Cat 03 patch
** but rather uses the "added" event and then checks to make sure it was the stage container the target was added to
interval - (default .1) time in seconds to check (also see ZIM TIME constant)
keeps repeating until stage is there or maxTime is reached
maxTime - (default null) time in seconds to keep checking or forever if not provided
RETURNS id of interval so clearInterval(id) will stop added() from checking for stage
CLOSE ▲PAGE ▤CODE ▤
centerReg
zim DisplayObject method
DESCRIPTION
Centers the registration point on the bounds - obj must have bounds set.
Will default to adding the object to the container.
If no container parameter is provided and the object is in a container,
centerReg will center the object in the current container. Thanks Bracer Jack for the suggestion.
If no container and the object is not in a container,
centerReg will center the object on the default frame's stage.
A convenience function for setting both registration points at once.
Also see center() for centering without changing the registration point.
Also see reg(CENTER) for the same effect but without adding to container
SEE: https://zimjs.com/positioningEXAMPLE
const rect = new Rectangle(100, 100, blue)
.centerReg() // centers registration, centers and adds to stage
.animate({obj:{rotation:360}, time:1, ease:"linear", loop:true});
// To just center the registration and not add it to a container
// use rect.centerReg(null, null, false);
// This is different than in the past where leaving out parameters would just center the registration
// The change is to match the default behaviour of addTo() and center() to add to stage without parameters
PARAMETERS supports DUO - parameters or single object with properties below
container - (default object's parent or if none, the first frame's stage) centers the object on and adds to the container
index - (default null) if provided will addChildAt the object at the index (0 being bottom)
will be ignored if the add parameter is false
add - (default true) set to false to only center the object's registration
setting to false will not remove the object if already added to a container
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
center
zim DisplayObject method
DESCRIPTION
Centers the object on the container.
Will default to adding the object to the container.
If no container parameter is provided and the object is in a container,
center will center the object in the current container. Thanks Bracer Jack for the suggestion.
If no container and the object is not in a container,
center will center the object on the default frame's stage.
Also see centerReg() for centering registration point at same time.
SEE: https://zimjs.com/positioningEXAMPLE
var rect = new Rectangle(100, 100, blue)
.center() // centers and adds to stage
// the below animation will be around the registration point at the top left corner
// this is usually not desired - see centerReg() when rotating and scaling
.animate({obj:{rotation:360}, time:1, ease:"linear", loop:true});
PARAMETERS supports DUO - parameters or single object with properties below
container - (default object's parent or if none, the first frame's stage) centers the object on and adds to the container
index - (default null) if provided will addChildAt the object at the index (0 being bottom)
will be ignored if the add parameter is false
add - (default true) set to false to only center and not add the object to the container
setting to false will not remove the object if already added to a container
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
place
zim DisplayObject method
DESCRIPTION
Sets the object to drag and logs to the console the x and y.
Also can use keyboard arrows for moving 1 pixel
and SHIFT keyboard arrows for moving 10 pixels.
This is for when building you can move an object around to position it
then when positioned, look at the console for the positioning code.
In your code, set the reported x and y and delete the place call.
EXAMPLE
circle.place("circle"); // lets you drag circle around - then see console
PARAMETERS
id - (default null) the name of the object so that the log gives you complete code
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
placeReg
zim DisplayObject method
DESCRIPTION
Gives draggable indicator to position a registration point in an object
This is for when building and when positioned, look at the console
for registration code and delete the placeReg call.
EXAMPLE
myContainer.placeReg("myContainer"); // lets you drag an indicator around - then see console
PARAMETERS
id - (default null) the name of the object so that the log gives you complete code
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
obj.pos(x, y, horizontal, vertical, container, index, add, reg, regX, regY)
pos
zim DisplayObject method
DESCRIPTION
Chainable convenience function to position an object and optionally add to a container
pos() provides easy positioning around the edges of a container.
pos() has gone through three versions:
VERSION 1 - positioned the registration point and has been replaced with loc()
VERSION 2 - positioned left, right top or bottom with right and bottom being specified with boolean true
VERSION 3 - positions left, right, center, top and bottom with ZIM positioning constants
pos() positions objects from the edges of the container or on the stage if no container provided
This defaults to the left of the object from the left and the top of the object from the top
If the horizontal parameter is set to RIGHT it will position the right of the object from the right of the container
If the vertical parameter is set to BOTTOM it will position the bottom of the object from the bottom of the container
If CENTER is provided, it centers the object on the axis and then moves it the x or y provided
Setting reg (or regX, regY) to true will position to the registration point - also see POSREG constant
SEE: https://zimjs.com/positioningEXAMPLE
// 1. adds circle to default stage moves left and top of circle to 100, 100
circle1.pos(100, 100);
// 2. adds circle to box and positions right and bottom of circle 100 and 200
// from right and bottom of box bounds
circle2.pos(100, 200, RIGHT, BOTTOM, box)
// or
circle2.pos(100, 200, RIGHT, "bottom", box)
// or
circle2.pos(100, 200, true, true, box);
// 3. centers the circle in x and moves 100 and places circle 200 from bottom
circle3.pos(100, 200, CENTER, BOTTOM);
// 4. adds to stage and puts registration point at x=200 and y=0
circle4.pos({x:200, reg:true});
// 5. adds to stage and puts registration point at x=200 and y=radius (not y=0)
circle5.pos({x:200, regX:true});
PARAMETERS supports DUO - parameters or single object with properties below
x - (default null or 0 for right) the x distance in the container to the left or right side of the object
which side, depends on the right parameter
if reg or regX is true then it is the distance to the registration point not the side
y - (default null or 0 for bottom) the y distance in the container to the top or bottom of the object
which one, depends on the bottom parameter
if reg or regY is true then it is the distance to the registration point not the top or bottom
horizontal - (default LEFT) LEFT will position the left side to the left side of the container bounds
set to RIGHT to postion the right side from the right of the container bounds
if reg or regX is true then it is the distance to the registration point not the side
set to CENTER or MIDDLE to center object and move amount provided in x
if reg or regX is true then centers the registration point and moves the amount provided in x
set to START to position LEFT for ZIM DIR constant is "ltr" or RIGHT when DIR="rtl" - END is the opposite
vertical - (default TOP) TOP will position the top side to the top side of the container bounds
set to BOTTOM to postion the bottom side from the bottom of the container bounds
if reg or regY is true then it is the distance to the registration point not the side
set to CENTER or MIDDLE to center object and move amount provided in y
if reg or regY is true then centers the registration point and moves the amount provided in y
container - (default current container or zdf stage) the Container to add the obj to and position
index - (default null) if provided will addChildAt the object at the index (0 being bottom)
add - (default true) add to container - set to false to not add
reg - (default false) set to true to position to the registration point rather than sides, top or bottom
See: POSREG contant - set POSREG=true; to change the default pos() to position the registration point
This is good to adjust legacy code - or if the original pos setting is preferred.
regX - (default reg) set to true to position x to the registration point rather than the sides
will override reg if provided
regY - (default reg) set to true to position y to the registration point rather than the top or bottom
will override reg if provided
PROPERTIES
zimPos - added to the obj and holds an object with the initial pos() parameter values as follows:
{x,y,h,v,i} for x, y, horizontal, vertical and index.
note: to get the container ask for the obj parent property
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
EXPAND ▼ obj.loc(target|x, y, container, index, add, localToLocal)
obj.loc(target|x, y, container, index, add, localToLocal)
loc
zim DisplayObject method
DESCRIPTION
locates obj registration at registration of provided target
or at x and y if numbers are provided
This is like the original pos() where the registration is used
But it a single object with x y properties can be passed as a parameter
Will calculate localToLocal if target is provided
Also can add to container at an index
SEE: https://zimjs.com/positioningEXAMPLE
const circle1 = new Circle().pos(100,100);
const circle2 = new Circle().loc(circle1); // adds on top of circle1
EXAMPLE
new Circle().loc(400, 400); // places reg of circle at 400, 400
// note, this is different than pos(400, 400) which would place left top of circle at 400, 400
PARAMETERS supports DUO - parameters or single object with properties below
target | x - (default null) an object with x and y properties such as any ZIM Display Object (Rectangle, Button, etc)
or a zim Point(100, 100) object or {x:100, y:300}, etc.
or an Array with an x and y value [100,300]
or can be a Number for an x value - in which case, a y value might be expected too
y - (default null) an optional y value
container - (default current container or zdf stage) the Container to add the obj to and position
index - (default null) if provided will addChildAt the object at the index (0 being bottom)
add - (default true) add to container - set to false to not add
localToLocal - (default true) if target is provided, the obj will be placed on the target matching locations across coordiate spaces
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
mov
zim DisplayObject method
DESCRIPTION
Move the object over in the x and/or y
Equivalant to obj.x += x and obj.y += y
Pass in 0 for no shift in x if you just want to shift y
Gives chainable relative position
SEE: https://zimjs.com/positioningEXAMPLE
new Circle().center().mov(50); // move to right 50
PARAMETERS supports DUO - parameters or single object with properties below
x - (default 0) the distance in x to move (can be negative)
y - (default 0) the distance in y to move (can be negative)
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
sca
zim DisplayObject method
DESCRIPTION
Chainable convenience function to do scaleX and scaleY in one call.
If you pass in just the scale parameter, it scales both x and y to this value.
If you pass in scale and scaleY then it scales x and y independently.
Also see scaleTo(), fit() and Layout().
EXAMPLE
circle.sca(.5); // x and y scale to .5
circle.sca(.5, 2); // x scale to .5 and y scale to 2
PARAMETERS
scale - the scale (1 being full scale, 2 being twice as big, etc.)
scaleY - (default null) pass this in to scale x and y independently
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
alp
zim DisplayObject method
DESCRIPTION
Chainable convenience function to set the alpha
See also the CreateJS set({prop:val, prop2:val}) method;
See also vis() and visible to keep hitTests as alp(0) does not
EXAMPLE
new Circle(100, red).center().ble("difference");
// note: a blendMode will not work against the background color of the canvas
// if this is desired, add a rectangle onto the stage to start
new Rectangle(W, H, F.color).addTo();
new Circle(100, red).center().ble("difference");
PARAMETERS
blendMode - (default "difference") the blendMode string:
normal, multiply, screen, overlay, darken, lighten
color-dodge, color-burn, hard-light, soft-light
difference, exclusion, hue, saturation, color, luminosity
OR the compositeOperation string:
source-over, source-in, source-out, source-atop,
destination-over, destination-in, destination-out, destination-atop,
copy, xor
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
dye
zim DisplayObject method
DESCRIPTION
Chainable convenience function to set the color of a shape
or the backgroundColor of an object with backgroundColor
Also see color and backgroundColor properties
EXAMPLE
circle.dye(red); // same as circle.color = red;
button.dye(blue); // same as button.backgroundColor = blue;
PARAMETERS
color - a ZIM or HTML color - green, "blue", "#333", etc.
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
hov
zim DisplayObject method
DESCRIPTION
Chainable convenience function to set the rollover (hover) property of an object
This defaults to alpha if a number and color if a string
But the type of property can also be set - for multiple properties, use a Button
This sets mouseover and mouseout events on the object
It will also set the cursor of the object to "pointer"
This can be changed with the cursor property or the cur() method
EXAMPLE
new Circle().center().alp(.5).hov(.8);
new Rectangle(100,100,blue).center().hov(green);
new Triangle().center().hov(1.5, "scale");
PARAMETERS
value - (default 1) the hover value of the property
if a number, the default property is alpha
if a string, the default property is color
passing in -1 will remove the hover
prop - (default alpha or color as stated above) the property to change to the value on hover
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
rot
zim DisplayObject method
DESCRIPTION
Chainable convenience function to set the rotation
See also the CreateJS set({prop:val, prop2:val}) method;
EXAMPLE
new Rectangle().center().rot(180);
PARAMETERS
rotation - (default null) the rotation in degrees
x - (default regX) set an x value to rotate about
y - (default regY) set a y value to rotate about
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
siz
zim DisplayObject method
DESCRIPTION
Chainable convenience function to set width and height in one call.
If you pass in just the width or height parameter, it keeps the aspect ratio.
If you want to set only the width or height, then set only to true.
If you pass in both the width and height then it sets both.
Note: that width and height will adjust the scaleX and scaleY of the object.
Also see width, height, widthOnly, heightOnly.
EXAMPLE
const rect = new Rectangle(100,200,blue).addTo();
rect.siz(200); // sets width to 200 and height to 400
rect.siz(200, null, true); // sets width to 200 and leaves height at 200
rect.siz(200, 100); // sets width to 200 and height to 100
PARAMETERS
width - (default null) the width of the object
setting only the width will set the widht and keep the aspect ratio
unless the only parameter is set to true
height - (default null) the height of the object
setting only the width will set the widht and keep the aspect ratio
unless the only parameter is set to true
only - (default false) - defaults to keeping aspect ratio when one dimension set
set to true to scale only a single dimension (like widthOnly and heightOnly properties)
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤VIDS
ske
zim DisplayObject method
DESCRIPTION
Chainable convenience function to skewX and skewY (slant)
See also the CreateJS set({prop:val, prop2:val}) method;
EXAMPLE
new Circle().center().ske(20);
PARAMETERS
skewX - (default null) the x skew
skewY - (default null) the y skew
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
reg
zim DisplayObject method
DESCRIPTION
Chainable convenience function to regX and regY (registration point)
The registration point is the point the object is positioned with
and the object scales and rotates around the registration point
See also the CreateJS set({prop:val, prop2:val}) method;
See also centerReg()
NOTE
most rectangular objects have their registration at the top left
whereas most circular objects (not images, though) have their registration point in the center.
But this registration point can be moved anywhere.
See: https://codepen.io/zimjs/pen/qBEjYZVEXAMPLE
new Circle().reg(200, 200).center().outline(); // the circle in the outline() shows the registration point
EXAMPLE
new Rectangle().reg(RIGHT,BOTTOM).center(); // place reg at the bottom right corner
PARAMETERS
regX - (default null) the x registration as a number
or use LEFT, CENTER, RIGHT, START, END (for START and END, see DIR setting)
use CENTER with no regY to center both regX and regY
use CENTER for regX and DEFAULT for regY to only center regX
regY - (default null) the y registration as a number
or use TOP, CENTER, BOTTOM
still - (default false) set to true to move the object to counter the registration change
this will let you set the registration point without moving the object
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤BITS VIDS
top
zim DisplayObject method
DESCRIPTION
Places object on top layer in container - if in a container
returns the object for chaining
Can also just addTo(container) to re-add to top
NOTE for some situations this will break code
so a safer way is obj.parent.setChildIndex(obj, obj.parent.numChildren-1);
which is what this method uses
EXAMPLE
const circle = new Circle(100, red).center();
new Rectangle(200,200,blue).center();
circle.top(); // brings circle to the top of parent container - in this case, the stage
ord
zim DisplayObject method
DESCRIPTION
Moves object layer order in container - if in a container
returns the object for chaining
EXAMPLE
circle.bot().ord(1); // put circle one layer up from bottom of parent container
circle.top().ord(-2); // put circle two layers down from top (third highest layer)
PARAMETERS
num - (default 0) the number of levels (layers) up or down to move the object
1 will move the object one level higher, -1 will move it one level lower
2 will move the object two levels higher, -2 will be two levels lower, etc.
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
cur
zim DisplayObject method
DESCRIPTION
Chainable function that sets the object's cursor to the type provided - same as CSS cursors.
NOTE
if using drag(), it will set its own cursor, so use the dragCursor parameter in that case.
NOTE
there are also custom cursors as the cursors property of Frame.
EXAMPLE
const circle = new Circle(10, red).center().cur(); // "pointer"
circle.on("click", ()=>{zog("yes");});
sha
zim DisplayObject method
DESCRIPTION
Chainable function that sets the object's drop shadow to a CreateJS Shadow indirectly or directly
EXAMPLE
// indirectly set the CreateJS Shadow
// with sha(color, offsetX, offsetY, blur)
const circle = new Circle(10, red).center().sha("rgba(0,0,0,.2)", 10, 5, 5);
// directly set the CreateJS Shadow
// with sha(new createjs.Shadow())
const shadow = new createjs.Shadow("rgba(0,0,0,.2)", 10, 5, 5);
const circle1 = new Circle(10, "pink").center().mov(-30).sha(shadow);
const circle2 = new Circle(10, "yellow").center().mov(30).sha(shadow);
PARAMETERS
color||Shadow (default "rgba(0,0,0,.3)") the CSS color for the shadow - "red", dark, etc.
or pass a single parameter that is a CreateJS Shadow object https://www.createjs.com/docs/easeljs/classes/Shadow.html
pass in -1 to remove a shadow - remember to S.update()
offsetX (default .08 the width or 5 if no width) the distance in the x that the shadow is moved over - can be negatitve
offsetY (default .08 the height or 5 if no height) the distance in the y that the shadow is moved over - can be negatitve
blur (default .16 the width or 10 if no width) the distance the shadow is blurred
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤VIDS
dep
zim DisplayObject method
DESCRIPTION
A chainable method to set the depth property of a Display object for use with ZIM VR().
When the object is added to VR it will be cloned into two channels and shifted left and right based on its depth.
A depth of 0 will not shift the object and this will appear flat on the screen.
A depth of 20 will shift 20 pixels left and right and appear to come out of the screen.
A depth of -20 will appear to go into the screen.
Depending on the VR parallax settings, depth can also affect parallax.
A negative depth does not unless negativeParallax is set to true in the VR parameters.
EXAMPLE
new Circle().center().dep(10);
PARAMETERS
depth - (default 0) the apparent depth in ZIM VR - or set the depth property
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤VIDS
nam
zim DisplayObject method
DESCRIPTION
A chainable method to set the name property of a DisplayObject.
The object can then be accessed with object("name") (or zim.object("name") if zns is true)
BACKGROUND
CreateJS provides Containers with a name property and a getChildByName() method
but you have to remember to ask the parent container for the child and it is a little lengthy.
In ZIM Cat 01, nam() and object() were introduced as a global way to handle object names.
Usually, a variable name is used to reference objects but the name offers an alternative.
Note: naming an object with the same name will overwrite earlier names accessible through object()
This will NOT remove the name property from the previous object
So it is possible that the previous object can still be accessed with parent.getChildByName()
parent.getChildByName() will find the first child with that name in the container
object() will find the last named object with that name anywhere
We could remove previous name properties with the same name but we decided not to
Let us know your thoughts at https://forum.zimjs.comEXAMPLE
new Circle().nam("ball").center();
// see what names there are:
zog(object.getNames()); // ["ball"] - if only "ball" has been named
if (mobile()) object("ball").sca(2);
else object("ball").dispose();
zog(object.getNames()); // [] - if only "ball" has been named
object("ball").tap(e=>{
zog(e.target.name); // "ball"
});
PARAMETERS
name - a String to set the name property of the object
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
--------------INTERACTIONS, EFFECTS AND PHYSICS
EXPAND ▼ obj.movement(call)
movement
zim DisplayObject method
DESCRIPTION
Chainable convenience method that captures mouse movement over an object.
This triggers when a mouseover is active and stagemousemovement dispatches.
It also triggers when a pressmove dispatches - so good for mobile.
A callback function is called on movement.
NOTE
set an object's noMovement property to true to remove these events
SEE: noMovement() as well
EXAMPLE
obj.tap(call, distance, time, once, dbl, dblTime, call2, call3, call4)
tap
zim DisplayObject method
DESCRIPTION
Chainable convenience method that adds a mousedown and mouseup event to the object
that requires the to move less than distance parameter
This is more like a proper click - down up without dragging.
This method works on desktop or mobile, etc.
An optional time parameter is provided if a minimum time is desired.
Note that a click event also works on mobile as a "tap"
but click also allows dragging between down and up presses - so really is a mouseup.
This will automatically add a cursor of "pointer"
which can be changed with the cursor property or cur() method
When dbl is set to true call will be called when a double tap occurs
With this setting, tap also handles either a single or double tap by providing call3 or call4.
call3 will call if a single tap happens regardless of whether there is a double tap or not
call4 will call if a single tap happens and there is no double tap
this means it waits for the double tap time to fail and then calls call4
To give a more responsive single tap it reduces the default dblTime value
NOTE
tap() ignores List titleBar and organizer as to not conflict with tapping on actual list
NOTE
set an object's noTap property to true to avoid activating a hold on an object
SEE: noTap() as well
EXAMPLE
new Circle(50, red).tap(e=>{
e.target.alpha = .5;
S.update();
});
EXAMPLE
new Button().tap(()=>{
zgo("https://zimjs.com", "_blank"); // open ZIM site in new tab
});
EXAMPLE
// wanting to do one thing on single tap and another thing on double tap on same object
// this will set the default dblTime to .5 seconds (rather than 1 second)
new Rectangle().center().tap({
dbl:true,
call:()=>{
// do double tap code
S.update();
},
call4:()=>{
// do single tap code
S.update();
}
});
PARAMETERS supports DUO - parameters or single object with properties below
call - the function to call when clicked
call will receive the event object as a parameter (with target, currentTarget, etc. properties)
distance - (default 5 or 10 if dbl is true) distance in pixels within which the mouseup must occur for a click to be counted
if dbl is true it will lengthen the default distance to give an easier double tap
time - (default 8) time in seconds within which the mouseup must occur for a click to be counted - also see TIME constant
once - (default false) set to true to capture only one click then auto-remove listeners
dbl - (default false) set to true to capture a double click - this works on mobile where dblclick may not
dblTime - (default 1 or .5 if call4) time in seconds from first pressup to pressup a second time to count as a double tap - also see TIME constant
if call4 is provided it will shorten the default dbl tap time to give a more responsive single tap alternative
call2 - (default null) a function to call on pressup if a tap is not made
call3 - (default null) with dbl set to true, a function to call on single tap regardless of a double tap or not
call4 - (default null) with dbl set to true, a function to call on single tap only if double tap fails
cursor - (default pointer) set to a CSS cursor or false if not wanting to set cursor on tap
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
hold
zim DisplayObject method
DESCRIPTION
Chainable convenience method that adds a press and hold event to the object
The callback function will run after the object is held for a certain time without moving the object
This method can be used on mobile to replace shift keys, etc.
This will automatically add a cursor of "pointer" - although mobile will not see it
which can be changed with the cursor property or cur() method
NOTE
set an object's noHold property to true to avoid activating a hold on an object
SEE: noHold() as well
EXAMPLE
// remove circle if held for 1000 ms (one second)
new Circle(50, red).hold(e=>{
e.target.removeFrom();
S.update();
});
PARAMETERS
call - the function to call after hold time
call will receive the event object as a parameter (with target, currentTarget, etc. properties)
distance - (default 5) distance in pixels within which the mouseup must occur for a hold to be counted
time - (default 1.5) time in seconds before hold is activated
once - (default false) set to true to capture only one click then auto-remove listeners
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
change
zim DisplayObject method
DESCRIPTION
Chainable convenience method that adds a change event to the object
This only works for components that dispatch a change event ;-)
SEE: noChange() as well
EXAMPLE
new Tabs().change(e=>{
zog(e.target.text); // the text of the selected tab
});
PARAMETERS
call - the function to call when changed
call will receive the event object as a parameter (with target, currentTarget, etc. properties)
once - (default false) set to true to capture only one click then auto-remove listeners
RETURNS obj for chaining
CLOSE ▲PAGE ▤CODE ▤
drag
zim DisplayObject method
DESCRIPTION
Adds drag and drop to an object with a variety of options.
Handles scaled, rotated nested objects.
Also see draggable property for setting a default drag() and noDrag()
and to indicate whether a drag has been set.
NOTE
drag() will stop ZIM Swipe() from triggering a swipe event.
Set the overridNoSwipe parameter of ZIM Swipe() to true to capture swipe events.
NOTE
also see the draggable property - set to true for basic drag() and false for noDrag()
EXAMPLE
const radius = 50;
const circle = new Circle(radius, red);
circle.center();
circle.drag();
// OR with chaining
new Circle(radius, red).center().drag();
// OR with ZIM DUO
circle.drag({slide:true});
// BOUNDARY
// circle has its registration point in the middle
// keep registration point within rectangle starting at x=100, y=100
// and drag within a width of 500 and height of 400
const boundary = new Boundary(100,100,500,400);
circle.drag(boundary);
// or keep circle on the stage with the following
const boundary = new Boundary(0,0,W,H).contract(radius);
circle.drag(boundary); // drag within stage
// or by passing the stage (or a Container as a boundary)
circle.drag(S); // drag within stage
EXAMPLE
// dragging only horizontal or vertical at a time
const circle = new Circle(50,red).center().drag();
circle.on("mousedown", ()=>{
const start = {x:circle.x, y:circle.y};
circle.on("pressmove",()=>{
timeout(.01, ()=>{ // works without but this gives a little better feel
let horizontal = Math.abs(circle.x-start.x) >= Math.abs(circle.y-start.y);
let boundary = horizontal?new Boundary(0, start.y, W, 0):new Boundary(start.x, 0, 0, H);
circle.dragBoundary(boundary);
});
}, null, true); // once
});
circle.on("pressup", ()=>{circle.dragBoundary()});
PARAMETERS supports DUO - parameters or single object with properties below
boundary - (default null) a ZIM Boundary object for the drag boundary
or a ZIM DisplayObject including stage
If the boundary is a display object then ZIM will keep the shape of the dragged object inside the bounds.
If the boundary object is a Blob then the dragged object will stay within the Blob (experimental).
If the boundary object is a Circle then the registration point of the dragged object will stay within the circle
If the object being dragged is a Pic() then make sure it is preloaded or has dimensions before adding a drag boundary
If the drag is on a container and the "all" parameter is false
then ZIM will call drag methods on each child so the bound calculations are easier.
The drags will be applied after a .05 second delay allowing items to be added directly after.
Alternatively, drag() can be placed on the container AFTER the objects are added
and the immediateBoundary parameter set to true. Or drag() can be applied manually on each child.
a boundary with 0 width will drag vertically. A boundary with 0 height will drag horizontally
or see the axis parameter
note: boundary will only work in 90-degree-rotated containers - as such, do slant Window and List, etc.
If surround is true then it will make sure the obj surrounds the boundary rather than stays within it
This boundary is relative to the stage (global).
If a boundary relative to the object's parent is desired then set the localBoundary parameter to true.
Rectangle, Stage, StageGL - will keep object fully inside the bounds (based on bounds of object when adding drag).
axis - (default BOTH) or HORIZONTAL or VERTICAL - set the axis of the drag
also see the boundary parameter where the width can be set to 0 for vertical dragging with a limit of y and the height
or the height can be set to 0 for horizontal dragging with limit of x and the width
overCursor - (default "pointer") the CSS cursor property as a string for rolling over the object
dragCursor - (default "pointer") the CSS cursor property as a string for pressing and dragging the object
all - (default false) set to true to drag a whole container rather than its parts (was called currentTarget)
eg. container.drag(); will drag any object within the container
container.drag({all:true}) will drag the whole container
See: DRAGALL contant - set DRAGALL=true; to change the default drag to drag a whole container
swipe - (default false) which prevents a swipe from triggering when dragging
localBoundary - (default false) which means the rect is global - set to true for a rect in