Releases: danzen/zimjs
ZIM 018
ZIM is a general canvas framework at https://zimjs.com - official updates are at https://zimjs.com/updates.html
Welcome to ZIM 018!
1. HAND TRACKING WITH ML5 AND ZIM CAM
https://zimjs.com/018/handtrack.html
A handTrack(ML5results) method has been added to ZIM Cam(). Must import zim_cam.
By default, this replaces the normal mouse and touch when a hand is detected.
Each pointer finger is a cursor for mousemove, mouseover and mouseout
and pinching the pointer finger and the thumb, triggers mousedown, pressmove, pressup, tap, and click.
There is a cursorMode which defaults to AUTO - there are also true and false values.
CURSOR MODES
In all cases, the hand cursors still show, have data, and dispatch events.
The cursorMode property can be used to change the mode dynamically. There is also a toggleReplace parameter and property (default true) which lets the user toggle using the hand rather than mouse and press but pinchin thumb and pinky. When a hand replaces the mouse and touch, the cam.replaceCursor is true as is the zim.handCursor. When the mouse and touch are being used then cam.replaceCursor and zim.handCursor are false. The handTrack() method automatically calls a prepareTrack() method if prepareTrack() is not already called. Optionally, the prepareTrack() can be called first to set a variety of options including the cursorMode parameter. The tracking cursors will still show and the cam dispatches "handmove", "handdown", and "handup" events.
// INSIDE A CAM ASK - see docs for Cam()
// optional - use prepareTrack() with the following parameters:
// width, height, hand, pinchColor, pinchHide, leftColor, rightColor,
// handScale, handAlpha, damp, gapTime, tapTime, cursorMode, toggleReplace
// cam.prepareTrack();
// ML5
const handPose = ml5.handPose(modelLoaded);
function modelLoaded() {
handPose.detectStart(cam.getCanvas(), result);
function result(results) {
// handTrack() replaces mouse and touch
// with hand and pinch interaction if a hand is detected
// prepareTrack() is automatically called
cam.handTrack(results);
}
}
WORKINGS
When replaceCursor is true, We pass the finger location directly into CreateJS.
We use the remoteCursor system that we made in CreateJS for handling TextureActive raycast data from threejs.
The ZIM cam module alreay had a CamCursor() class... but it is custom pixel tracking and a little slow.
The ML5 Tracking is the best we have seen... and we have been doing this for 20 years (back in Flash).
2. ML5 EXAMPLES IN ZIM
ML5 - Machine Learning library at https://ml5js.org/
has a bunch of AI features built on TensorFlow - from Google AI.
We have made a mini-site demonstrating most but not all features.
ML5 EXAMPLES
ML5 can give very accurate hand poses, face poses and body poses and results return points.
These points can be used to place ZIM objects or with a ZIM Shape to make circles, etc.
There are other features too like shape recognition, blurring backgrounds, etc.
These can all be used in ZIM - for using ML5 for interaction see the HAND TRACKING section above.
3. ZIM CAROUSEL3D
https://zimjs.com/018/carousel3D.html
A 3D carousel that cycles through items as it is swiped
or using next(), prev() or go() methods or index property.
Can be horizontal or vertical.
// widthFactor 2.5 will spread the items more in the width
// heightFactor 10 will increase height difference
// curve .6 will curve them a little more
const carousel = new zim.Carousel3D(700, 500, pages, 2.5, 10, .6)
.center()
.change(()=>{
indicator.index = carousel.index;
});
// optional indicator
const indicator = new Indicator({
width:pages.length*20,
height:25,
num:pages.length,
interactive:true,
toggleFirst:false,
delayLights:true
}).pos(0,80,CENTER,BOTTOM).change(()=>{
carousel.go(indicator.index);
});
// optional arrows
new Arrow().pos(50,0,RIGHT,CENTER).tap(()=>{
carousel.next();
});
new Arrow().rot(180).pos(50,0,LEFT,CENTER).tap(()=>{
carousel.prev();
});
new Frame(FIT, 1024, 768, light, dark, ready, "stats.json");
function ready() {
zog( new Dat("stats.json").data ) // a JSON parsed object
}
5. ZIM PHYSICS PUPPET
https://zimjs.com/018/puppet.html
Normally, objects with physics should not be animated or dragged with ZIM
but rather they should be moved with physics forces or the physics drag.
Now, we can use puppet() to make an object with physics follow an object without physics.
The object without physics can be animated, wiggled, dragged with ZIM drag(), etc.
and the object with physics will be joined with the equivilant of a mouseJoin
objectWithPhysics.puppet(objectWithoutPhysics) - there is also puppetOff().
Then animate(), wiggle(), zim drag(), gesture(), transform(), etc. can be used.
note: it is the x and y property only, not rotation or scale.
// make sure to import zim_physics
new Physics();
const circle = new Circle(20,red)
.center()
.wiggle("x", null, 100,200,1,2)
.wiggle("y", null, 100,200,1,2); // note - no physics
const ring = new Circle(100,clear,purple,2)
.center()
.addPhysics()
.puppet(circle); // ring will follow circle
new Rectangle(100,100,purple)
.reg(CENTER)
.center()
.mov(50,50)
.addPhysics(false); // static
- LABEL LETTERS IMPROVEMENTS
https://zimjs.com/018/justify.html
Added labelWidth to LabelLetters to line break at LabelWidth
Added lineAlign JUSTIFY to LabelLetters and lineAlignLast parameters.
Added JUSTIFY to global variables
new LabelLetters({
label: "Will this wind be so mighty as to lay low the mountains of the uuuug?",
lineWidth: 400,
lineAlign:JUSTIFY,
// lineAlignLast:JUSTIFY, // or LEFT, RIGHT, CENTER
});
7. ZIM MOTIONCONTROLLER TILEOBJ
https://zimjs.com/018/tileobj.html
Added tileObj to MotionController for keydown, dPad, gamebutton, and gamestick
Added moveGrid property to get or set the allowed moves specified by the tileObj
This let users move an object on a tile game board. Off-limit tiles can also be set.
This is not path finding - for path finding, use the game module Board with EasyStar.
const tileObj = {
animate:true,
cols:10,
rows:4,
w:70,
h:70,
spacingH:3,
spacingV:3,
startCol:1,
startRow:1,
moves:[
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,0,1,1,1,1],
[1,1,1,0,0,0,0,0,1,1],
[1,1,0,0,0,0,0,1,1,1],
[1,1,1,1,0,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1]
]
}
if (tileObj.moves) {
tileObj.cols = tileObj.moves[0].length;
tileObj.rows = tileObj.moves.length;
}
const tile = new Tile(
new Rectangle(tileObj.w,tileObj.h,white).reg(CENTER),
tileObj.cols,tileObj.rows,
tileObj.spacingH,tileObj.spacingV
)
.alp(.8)
.center();
// hide tiles that are off limits
if (tileObj.moves) {
loop(tile.items2D, (row,j)=>{
loop(row, (item,i)=>{
if (!tileObj.moves[j][i]) item.color = clear;
});
});
}
const player = new Circle(25,red).loc(tile.items[1]);
new MotionController({target:player, damp:1, type:dPad, tileObj:tileObj});
8. PERMISSIONASK
Removed ZIM Frame() sensors parameter and added creating the events to PermissionAsk()
So now, always use PermissionAsk() for cam, mic, devicemotion, or deviceorientation events
Tidied up the code for PermissionAsk().
const ask = new CamAsk().show(yes=>{
// if the user answers yes to the CamAsk
if (yes) {
// new Cam() will trigger the Browser asking for permission
// unless already have given permission in this session
let cam = new Cam(1280,720);
cam.on("ready", ()=>{
// code here
cam.scaleTo().center().alp(.2);
});
// if the user does not accept the browser asking...
ZIM 017
0. BUBBLING VIDS
https://www.youtube.com/watch?v=yfgpkRGkwXc - ZIM 017 Has Launched!
https://www.youtube.com/watch?v=i4GyEDK-W6Q - ZIM Chat Bot for AI Coding
https://www.youtube.com/watch?v=BQUrLWlLHv4 - Rive Integration - Interactive Graphics Tool
https://www.youtube.com/watch?v=WBvLtb9d3HM - Outline Image and Concave Physics
https://www.youtube.com/watch?v=ZCiR8lMwR4g - Accordion, Indicator, Continuous Pages updates
https://www.youtube.com/watch?v=X4ius2KLY74 - General Updates
https://www.youtube.com/watch?v=-OTI4l2zY7M - Data to and from NodeJS
https://www.youtube.com/watch?v=WC4fAcr2EUw - Drop with Drag and Lists
https://www.youtube.com/watch?v=R81uUfEsiOc - Slicer for n-Slicing and 9-Slicing
1. CHAT BOT
Created and AI Chat Bot for ZIM.
This uses RAG (Retrieval Augmented Generation)
which uses the best 3 questions and answers from 1000 ZIM question and answers
and the ZIM Template to feed to ChatGPT a special prompt.
The project was done by Suha Islaih https://www.linkedin.com/in/suha-islaih
and we would recommend employing Suha for similar projects.
The 1000 questions and answers were guided by the ZIM team
to get current information as raw ChatGPT was quite out-of-date.
From our tests, we greatly improved the answers from about 2% correct to 80% correct.
Still, that leaves 20% incorrect and possibly quite misleading.
We have included a poll at the bottom that you can do for each question
and which shows live results as to the correctness of the answers.
ZIM STATEMENT ON AI
We love coding and would much rather code than have AI code.
We love creating which is the process from idea to product/service.
How much of that is AI is up to you and your situation.
We would feel sad if people just use AI and do not code.
Initially, we considered saying that using AI is like eating without tasting.
But... if there is no expression in coding as in, it can be automated,
then we should let it be so, and spend time on more ideas, friends, life, etc.
Still, many like to cook even though we can just buy meals.
Code if you want. Use AI if you want.
2. RIVE INTEGRATION
https://zimjs.com/rive/animate.html
https://zimjs.com/rive/input.html
https://zimjs.com/rive/node.html
https://zimjs.com/rive/listen.html
Rive lets you make interactive graphics and animations - https://rive.app/
Rive is an animation tool similar to Adobe Animate (Flash) but with a special StateMachine
that has a cool connector node system to guide animation states.
Personally, I have done interactive animations for years on lots of tools
but at tenth glance, the StateMachine still confuses me ;-). Education would help, I am sure.
Most of these Rive animations can just be done in ZIM - but bones are nice!
Rive apps can be displayed in ZIM using one of two classes under META in Docs (along with QR and GIF)
The listener version takes a few seconds to load the WASM code and then is quick.
The Rive JS runtime script or import must be placed at the top of the HTML page.
// at top (note: fix the gap between the h and t below)
<script src="https://unpkg.com/@rive-app/canvas@2.17.3"></script>
// in ZIM code
// Rive, when not used in ZIM, requires an existing canvas and a canvas parameter.
// With Rive in ZIM, we make the canvas based on width and height parameters.
// A canvas parameter is available as well for a predefined canvas.
const r = new Rive({
src: "rive.riv",
width: 500,
height: 500,
autoplay: true,
stateMachines: "bumpy", // optional
});
// The Rive object has a display property that is a ZIM DisplayObject - a dynamic Bitmap.
// The ZIM Vid() is also a dynamic Bitmap but the difference is the Vid is the Bitmap.
// With Rive, the Rive object is a Rive object so you cannot add it to the stage, for instance.
// You must add the display property to the stage.
// This lets people use the Rive object with all its methods and properties just like in examples.
// For any ZIM methods like center(), animate(), etc. we use the display property of the Rive object.
r.display.center();
3. VALUE AND INDEX
currentValue has been replaced with value and selectedIndex with index.
currentValue and selectedValue will still work for backwards compatibility.
This is for parameters, properties and STYLE of components such as RadioButton, Slider, etc.
Note: not all components with a value have an index and visa versa, although some have both.
STYLE = {index:1}
const r = new RadioButtons().addTo().change(()=>{
zog(r.index)
});
- DROP FOR LIST AND DRAG
https://zimjs.com/017/canvas.html
https://zimjs.com/017/dropping.html
We can now drag and drop items from one list to another.
And from a list to a target display object and from a display object to a list.
And in general drop any display object onto another target display object.
The dropping example above shows dropping in and out of lists.
The two code examples below have dropping between lists and without lists.
// between Lists
const w = 60;
const h = 60;
STYLE = {
Rectangle:{width:w, height:h, color:series(blue,green,orange,yellow,pink)},
List:{vertical:false, spacing:null, viewNum:9, drop:true}
}
const items = [];
loop(40,()=>{items.push(new Rectangle())})
const list = new List(600, h*1.5, items).center().mov(0, -100);
const items2 = [];
loop(40,()=>{items2.push(new Rectangle())})
const list2 = new List(600, h*1.5, items2).center().mov(0,100);
list.dropTargets = list2;
list2.dropTargets = list;
// with just drag()
const rectangles = new Tile(new Rectangle(130,130).reg(CENTER),3,1,50,0).pos(0,100,CENTER,CENTER);
new Tile(new Circle(50,series(red,blue,pink)),3,1,70,0).pos(0,-100,CENTER,CENTER).drag({
dropTargets:rectangles.items,
// dropEnd:false,
// dropCopy:true,
// dropBack:false // and more!
});
See the many drop parameters of List() and drag() - these are quite similar.
// LIST
drop - get or set to allow drag and drop of items onto the current lists - see drop parameter
dropTargets - get or set a list or an array of lists to drop an item from the current list - see dropTargets parameter
dropColor - get or set the color of the diamond reticle that indicates where an item will be dropped - see dropColor
dropReticle - each list that can be dropped on gets a dropReticle property that is the ZIM rectangle
so individual reticles can be adjusted - say different colors for different lists
dropItem - after a dropdown event, the dropItem is the ghost being dragged
dropIndex - after a dropdown event, the dropIndex is the original index of the item being dragged
dropTarget - after a dropup event, the dropTarget is the object the item was dropped into (could be original list)
dropNewIndex - after a dropup event, the dropNewIndex is the index in the list the item has been dropped
// DRAG
dropTargets - an object or an array of objects that can receive a drop
this can be a List or a Container or a single object
if it is a list see the dropListProps as well to set reticle properties and scroll speed
dropCopy - (default false) make a copy of the object as it is being dragged
dropSnap - (default true) snap to the target object
dropBack - (default true) go back to start if not dropped on a target
dropEnd - (default true) once dropped on a target a noMouse() is set on the object
dropFull - (default true) do not drop on a full target
note - if the object is removed from the target then a drop can occur again on that target
dropHitTest - (default "bounds") can also be "reg", "circles", "circle", "rect" - see ZIM HitTests
dropScale - set a scale for the dropped object
dropWidth - set a width for the dropped object - overrides scale
height will keep aspect ratio unless dropHeight is provided
dropHeight - set a height for the dropped object - overrides scale
width will keep aspect ratio unless dropWidth is provided
Dropped objects have a dropTarget property saying which target was dropped on
and a dropList for which list, if any, the object came from.
5. N-SLICING
Added ZIM SlicedBitmap() to DisplayObjects, Slicer() to Components, and SlicerTypes() to Meta.
These work with n-slicing which is an advanced version of traditional 9-slicing.
The Slicer lets you make slices and types data to pass to a SlicedBitmap.
The SlicedBitmap can then have its slicesWidth and slicesHeight changed - and transform() now defaults to use these.
Certain regions will then be fixed, stretched or tiled depending on the types setting.
// Assuming a new Pic is preloaded
// slice the pic in four at 25% from the edges, scale the middle and keep the sides and corners not scaled.
new SlicedBitmap(1600, pic.height, pic, [[0.25,0.75],[0.25,0.75]], [[0,1,0],[0,1,0]])
.center()
.transform({minScaleX:.05, minScaleY:.05});
6. OUTLINE IMAGE
https://zimjs.com/017/outline.html
Added an outlineImage() function to the Code Module
that returns poi...
ZIM 016
1. SHADERS
https://zimjs.com/016/shaders.html
ZIM now supports shaders converted to 2D canvas as a dynamic Bitmap (similar to video in ZIM).
This means that shaders can be layered into ZIM features the same as other DisplayObjects.
// makes a gradient changing across the width
// note the multiline back tick quote - that is just JavaScript 6
// but inside is GLSL and in particular OpenGL shader coding language
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();
WHAT ARE SHADERS
Shaders have their own language GLSL to code the GPU (Graphical Processor Unit).
They are the basis of 3D and can also make very cool 2D effects!
The code is in two parts: Vertex Shaders and Fragment Shaders.
Vertex shaders control the points (vertices) of shapes (triangles).
Fragment Shaders control the color the pixels of the shapes.
We tend to use fragment shaders on the Canvas 2D.
The code is very low level and tricky so that it runs as fast as possible.
You will probably start by using existing code as there are lots of examples.
For instance - see ShaderToy:
https://www.shadertoy.com/
Also see the Docs for more information and examples:
https://zimjs.com/docs.html?item=Shaders
Note that the site banner is a shader that can be controlled with a little slider at right.
We control shaders from the outside with Uniforms (shader properties we can set)
2. EMITTER CONFIGURATOR
https://zimjs.com/016/emitter.html
On request, we have made an Emitter Configurator that uses sliders and checkboxes to set the many parameters,
visually see the results, and copy the resulting code.
Emitters can emit any DisplayObject as a particle
so not all configurations are shown here. Also the Shape option for the obj is not here.
See https://zimjs.com/docs.html?item=Emitter for more possibilities.
We are keeping ZIM a coding language rather than moving into an authoring environment like Flash.
Recall our discontinued (draft) visual editor https://zimjs.com/snips/
But perhaps we can make a few CONFIGURATORS over time - like for a Button next?
These we can list in the tools section - but will not call them raw tools like our set of tools so far:
Distill, Zapps, Wonder, AssetList and Doctor which are more HTML-based admin tools.
We have made a new line there for the Configurators.
3. NORMALIZE AND RATIO - IMPROVEMENT
https://zimjs.com/016/normalize.html
ZIM animate() with sequence animates each item in a container,
but this can be awkward when animating a tile for instance.
The sequence starts at to left and goes across the columns and down the rows.
Or a sequenceReverse will do the opposite.
But what about animating from the middle and out radially?
We noticed that GSAP was doing very cool effects from the center (or any sides) of containers.
Introducing the normalize() method and ratio property of a Container to solve this!
Normalize can take any property and assign a ratio for each child in a container
that is how close 1-0 that child is to the maximum property (among all the children).
Using a sequence time of 0 to animate each child individually
and setting the rate property relative to the ratio will have the same effect as the cool GSAP animations.
// animate based on how far from the center
// "reg" will also automatically adjust the registration points to the start position
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
});
The ratio can also be used on its own without animate().
For instance, the scale of the child could be set to the ratio
depending on how close it is to the center of the container.
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, // or make positive to avoid overlapping
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
4. SORTBY
https://zimjs.com/016/normalize.html
The Container now has a sortBy(prop, inverse) method to sort children levels based on a numeric property.
This uses the CreateJS sortChildren(sortFunction) but reduces thinking needed to construct the sortFunction.
However, if a more complex sort function is needed, then use sortChildren() - see CreateJS docs.
Also, see the last example up above where we sortBy("ratio")
Using sortBy("ratio", true); for inverse would make the middle objects behind the side objects.
5. RANGE - IMPROVEMENT
https://zimjs.com/016/range.html
ZIM Slider() now has a range parameter to set two buttons on the slider that give range values:
// SLIDER RANGE PARAMETERS
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 currentValue
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
SLIDER RANGE PROPERTIES
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.currentValue and rangeSliderB.currentValue
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
6. WIGGLE DEFAULT BASEAMOUNT AND END ON START - IMPROVEMENT
https://zimjs.com/docs.html?item=wiggle
ZIM wiggle() now has a default baseAmount that matches the property's current value
amd now ends on its start position if totalTime is set. Thanks Ami Hanya for the prompting.
There is an endOnStart parameter added to the end that defaults to true - set to false to not force end on start.
// the baseAmount parameter is null which means it will wiggle about the target's current x in this case
// after 4 seconds the circle will end its wiggle at the start x (in the center)
new Circle().centerReg().wiggle("x", null, 10, 100, .5, 1, 4);
7. NEW FORUM - IMPROVEMENT
ZIM has a new Forum and we will phase out Slack over the next couple months.
We are keeping Discord. There are two main reasons for moving:
The forum content will show in Web searches
The messages will persist and not be removed after three months
Discourse has been used for many tech communities including three.js, Cloudflare, FreeCodeCamp, OpenAI, etc. We hope you like it!
We will refer to this as the ZIM Forum, not Discourse, as we are still keeping Discord - and it would just be too confusing.
We will post the URL to the forum once we get settled there a bit more.
We are looking into setting up an invite system as well.
8. LABELWORDS - IMPROVEMENT
https://zimjs.com/016/labelwords.html
ZIM LabelWords() splits text up into individual word labels.
LabelWords is similar to LabelLetters but extends a Wrapper so it has all the settings of a Wrapper.
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().animate({
props:{scaleY:0},
time:.5,
rewind:true,
loop:true,
sequence:.1
});
9. OBJECTCONTROLS - IMPROVEMENT
https://zimjs.com/016/objectcontrols.html
ObjectControls were coded outside ZIM for three.js
We have added them automatically to the zim_three helper module.
They come fro...
ZIM 015
BUBBLING VIDEOS
https://www.youtube.com/watch?v=hy53jxlJ_nA - ZIM 015 - Animation Timeline Tool
https://www.youtube.com/watch?v=_oBfU92Q6fA - ZIM 015 - Emitter Warm
https://www.youtube.com/watch?v=fJMI_FJiQI4 - ZIM 015 - Continuous List and Carousel
https://www.youtube.com/watch?v=OQkIAYDz62Y - ZIM 015 - TextureActives 1 - with threejs
https://www.youtube.com/watch?v=us8TrX890rk - ZIM 015 - TextureActives 2 - with threejs
https://www.youtube.com/watch?v=G6uCnioPcRk - ZIM 015 - TextureActives 3 - the code
1. TEXTURE ACTIVES
ZIM IN THREEJS
ZIM can now be used inside three.js as an animated and interactive texture.
This is amazing as ZIM can now be used as interface in VR,
provide games and puzzles on any material on any mesh object
such as planes, boxes, cylinders, spheres, and models.
This includes everything in ZIM - components, emitter, dragging on paths, pen, etc.
Hopefully, this will introduce ZIM to the three.js community as well.
https://zimjs.com/015/textureactive.html - panel with various components
https://zimjs.com/015/textureactive_raw.html - same but without ZIM Three
https://zimjs.com/015/textureactive2.html - first person interactive cylinders
https://zimjs.com/015/textureactive3.html - model with scrambler
https://zimjs.com/015/textureactive4.html - HUD, Noise, Synth
https://zimjs.com/015/textureactive5.html - Physics
https://zimjs.com/015/textureactive_hud.html - HUD affecting three object
https://zimjs.com/015/textureactive_hud_raw.html - same but without ZIM Three
HOW IT WORKS
A TextureActive() class extends a ZIM Page() and prepares the needed settings.
A TextureActives() class (plural) manages these and matching three.js meshes
to capture x and y data on the mesh material with raycasting and pass the x and y to CreateJS.
CreateJS has been updated to 1.4.0 with a couple dozen new lines of code including
a createjs.remotePointers setting that turns off the regular DOM events and receives the three.js x and y.
The update() code in CreateJS has a single added conditional that tests for a createjs.remoteQueue array
and if so, updates the cache of any TextureActive objects and sets the required material update flag.
// TEXTUREACTIVE
// a TextureActive() is very much like a ZIM Page()
// it adds borderWidth, borderColor and corner
// also can specify animated and interactive - both default to true
const panel = new TextureActive({
width:W,
height:H,
color:white.toAlpha(.8),
corner:20
});
const circle = new Circle(100,red).center(panel).drag();
// from the ZIM Three helper module
const three = new Three({
width:window.innerWidth,
height:window.innerHeight,
cameraPosition:new THREE.Vector3(0,0,500),
textureActive:true
});
const renderer = three.renderer;
const scene = three.scene;
const camera = three.camera;
const controls = new OrbitControls(camera, three.canvas);
// TEXTUREACTIVES
// if more than one TextureActive object (likely) then pass in an array [panel, wall, arm, etc.]
const textureActives = new TextureActives(panel, THREE, three, renderer, scene, camera, controls);
const canvasWindow = three.makePanel(panel, textureActives);
scene.add(canvasWindow);
// there is now a three.js plane with a draggable circle on it
// orbitControls will let you move the camera around and it still drags perfectly!
// the code above looks simple but it was quite complex to achieve working with three different systems
// and once we got it working we reduced dozens of lines to just a few - in the normal ZIM fashion!
THREEJS
Above, we have used a makePanel() method in ZIM Three, that simplifies the three.js side
when a three.js Plane is needed. This is quite common for 2D like interfaces, games, puzzles, etc.
But makePanel() is optional. Otherwise on the three.js side everything is pretty well the same:
use a THREE.CanvasMaterial(textureActive.canvas) which gets mapped to a material as usual
the material is then meshed with the geometry and the mesh added to a scene again as usual
and the mesh is also added to the TextureActives() object with the addMesh() method.
AUTOMATIC
The TextureActives object receives the TextureActive objects
and matches these automatically to the provided meshes - as their material and textures are known.
The TextureActives does the raycasting which is a way to find x and y positions on the material of the 3D object.
These are passed in to CreateJS and replace the traditional mouse coordinates
in the very basic down, move and up functions in CreateJS which automatically flow through to ZIM.
The TextureActive objects are cached but we have recorded them for update in the CreateJS update (used by stage.update())
and the updateCache() and a three.js needsUpdating flag are done automatically.
This means there is no extra code needed in ZIM and minimal code in three.js.
VIEWER
A TextureActive object is just a ZIM Page - which is just a ZIM Container with a backing rectangle.
It is being mapped onto a three.js object but the ZIM object is still there on the stage.
We normally hide the stage but we have made a toggle key (t) to hide the three.js and show the ZIM stage.
This can be used during development to see and test the ZIM directly
and it is live - so any changes on the ZIM stage affect the three.js and visa versa.
The TextureActive objects are tiled horizontally and a slider and swiping is available to scroll through.
The TextureActive logo uses the toggle() method of the TextureActives manager property to toggle between the canvases.
This is controlled but a ZIM TextureActiveManager object that is made automatically when the first TextureActives object is made
it is available as the manager property of the TextureActives object
and has a toggle(state) method, a toggled property and a toggleKey property
ZIM TextureActive for interfaces, games, puzzles interactive texture in three.js
EXCEPTIONS
The ZIM custom cursor system works directly with window pointer events
and would need to be converted to receive the information from CreateJS.
It is very complicated as createjs toggles between DOM cursors, pointers and now the remotePointers from three.js
so at the moment, custom cursors is not available in TextureActive.
There can also only be one physics TextureActive although this can appear on any number of three.js materials.
2. THREE HELPER MODULE
https://zimjs.com/docs.html?item=Three
The ZIM Three module has been updated to 2.3 to accomodate the TextureActive system (above)
Added ortho, textureActive, colorSpace (THREE.LinearSRGBColorSpace),
colorManagement (false), legacyLights (false) to the end of the Three() parameters
The ortho sets up an orthographic camera and scene good for flat HUD elements or pop-ups
The textureActive parameter needs to be set to true to handle scaling for TextureActives
See the three.js links for
https://threejs.org/docs/#manual/en/introduction/Color-management
https://discourse.threejs.org/t/updates-to-color-management-in-three-js-r152/50791
https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733/23
THREEJS UPDATE
The version of three.js has been updated to R155
and the colorSpace has been adjusted in recent three.js to default to linear
which needs some minor adjustments otherwise colors will be washed out.
So we have set the default colorspace to THREE.LinearSRGBColorSpace which should make things easier
Basically, light intensity needs to be multiplied by Math.PI (and perhaps increased we have found)
Could not get the PointLight to work so used a DirectionalLight
Try setting colorManagement to true in Three() and see which you like better - will have to adjust intensity.
GLTF models were giving errors with colorManagement which is why the default is false for now.
3. NPM, GITHUB, TYPESCRIPT
Updated our NPM format so that import and require work the traditional way for developers.
This was a solid week of work under the leadership of Yoan Herrera who did a fantastic job.
We would definitely recommend contacting @yoan Herrera on our Slack for this type of work.
GitHub has been adjusted to show the system where we can now publish to NPM from VS Code.
The ZIM package on NPM now includes:
- dist/zim.js - module for web target (React, Angular, Vue, Svelte, etc.)
- dist/zim.cjs - module for node
- combined/zim.js - ES6 module like the ZIM CDN - optional
There were adjustments to the Typings primarily to remove the duplicate set of defines,
do a final export and export globals. This does mean that classes will need to be imported
to see type hints when not using the zim namespace - they work by default for using the namespace.
TEMPLATES
Templates were made for popular dev environtments. The specific links below all are set for TypeScript
See the main TEMPLATES link and scroll down for formats without TypeScript (except for Angular)
TEMPLATES: https://github.com/yoanhg421/zimjs-templates
REACT: https://github.com/yoanhg421/zimjs-templates/tree/master/templates/react-zim-ts
VUE: https://github.com/yoanhg421/zimjs-templates/tree/master/templates/vue-zim-ts
ANGULAR: https://github.com/yoanhg421/zimjs-templates/tree/master/templates/angular-zim-ts
SVELTE: target=_blank>https://github.com/yoanhg421/zimjs-templates/tree/master/templates/svelte-zim-ts
4. TIMELINE
https://zimjs.com/015/timeline.html
Added a ...
ZIM 014
ZIM 014 - https://zimjs.com
ZIM has now moved to a three number major release 014. Past versions are ZIM ONE, TWO, TRI, 4TH, VEE, SIX, HEP, OCT, NIO, TEN, CAT, NFT, ZIM and now we have ZIM 014. We will continue to 015, etc. ZIM version ZIM 00, 01, 02 was fun while but we have decided to leave that system. Here are the updates which can be seen formatted here:
https://zimjs.com/updates.html
A large part of this update was external to the actual ZIM code including a STORE, SITE REDESIGN and EDITOR updates.
STORE
https://zimjs.com/store
Added a new STORE page to ZIM along the top.
And moved NEWS into ABOUT under VERSIONS section.
The Zapp Store has sample mobile / desktop apps made with ZIM and the PWA tool.
ZAPPS:
Dazzle Finger - https://zimjs.com/finger - finger follows path to make magic
Odd Robots - https://zimjs.com/robots - find the good and bad robots
Plasma Points - https://zimjs.com/points - collect plasma points
Leader Board - https://zimjs.com/board - top scores from the zapps
The Plasma Points zapp has 100 points available
You can collect them on pages in the site, by accomplishing social tasks
and by making a zapp in the ZIM Editor.
We hope you enjoy the Zapps - but it is also a demonstration
of using ZIM for mobile apps and things like collectables, logins, etc.
The four zapps were made in less than a month
along with all the other updates to ZIM and the site.
Now, go get some high scores!
NEW SITE HEADER
Added a new interactive banner to the site
The banner lets you change the vapourwave landscape
You can double click the blob points to change to curves
and the landscape is saved across pages and time
which is easy to do with ZIM Blob and TransformManager.
Plasma Pods animate giving a preview of the new ZIM Store.
Discord and Slack have been moved to the top right
and makes way for TikTok and Dev in the Social Media links
Come follow us!
NEW SITE
Made the font bigger on the home page and did a little rearranging.
Added the new STORE and EDITOR to the top nav bar
Removed the HOME link on the bar for space - click the logo to go home.
With Editor moved up from the Gold Bars, there is room for a TOP
gold bar at the bottom right to take you to the top!
The top nav bar still secretly links to the bottom if pressed off a link.
Moved the following pages into new 014 template with header and footer
Home, About, Examples, Learn, Code, Docs, Updates
Frame, InteractiveAnimation, Make NFTs, Zapps PWA Tool, Mobile, ZIM Shim for Animate
CDN page, ES6 and Script pages, Tips, Dark Papers, Typescript, Hints, NPM, MVC, Library, Base
Intro, Tips, Map, Zap, Lab, Creative Coding, College, Explore, Five
EDITOR
Added individual INFO pages to the Editor that have a preview image, info, and links to
full screen, editor, code, origin, share and print.
The info pages can properly be share, will show up in search engines, etc.
Thanks Ami Hanya for the suggestion.
The print page has the image, info and QR codes to INFO, FULL, EDITOR and CODE.
Thanks Karel Rosseel for the suggestion.
Added reference field to file for reference links to codepen / youtube / etc.
This is a single link - if more links are desired then add them to the description
Made links in the description automatically become clickable.
Added Origin concept to Editor - if code is transfered with the little yellow arrow
then a "forked" checkmark shows at the top.
This also keeps track of the zapp that it was copied from for reference on the info page.
You can uncheck the Forked checkbox if desired to clear this connection.
There is no getting the connection back if saved - just remake the fork if desired.
MOBILE SYSTEM KEYBOARD STAGE SHIFT
https://zimjs.com/014/keyboard.html
We have added an optional keyboardShift parameter for TextInput and TextArea - thanks Ami Hanya for request
The default is false for now, so must be turned on
This will for mobile when the stystem keyboard is activated
Currently, the TextArea text shifts - we are trying to adjust it but it is complex.
BREAK - the ZIM TextArea() now has the placeholder parameter moved and a text parameter added
after width and height and before size like the TextInput
GLOBAL CUSTOM CURSORS
https://zimjs.com/014/cursors.html
Frame now has a cursors property to apply custom cursors beyond CSS cursors.
F.cursors = {
default:DisplayObject,
pointer:DisplayObject,
alert:DisplayObject
etc.
}
If the CSS cursor name is used these will override the CSS cursors with the custom cursors
Any name is fine for custom cursors - for example:
F.cursors = {yellow:new Circle(10,yellow)}
new Pic("earth.png").center().cur("yellow"); // will add a yellow circle for the pic's cursor
Setting F.cursors = null; will clear the custom cursors.
Any cursor type not assigned will use the regular CSS cursor for the type.
For reference, the CSS cursor names are as follows:
CSS2 - auto, crosshair, default, help, move, pointer, progress, text, wait, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize
CSS3 - none, context-menu, cell, vertical-text, alias, copy, no-drop, not-allowed, ew-resize, ns-resize, nesw-resize, nwse-resize, col-resize, row-resize, all-scroll, grab, grabbing, zoom-in, zoom-out
ZIM uses pointer for most rollover, press, drag, move scenarios and default when not interacting.
There are various resize cursors with Transform.
NOTE: please use the cur() to set any cursors and not the cursor property.
This will add an _cursor property to the object to help keep track of the custom cursor.
We have adjusted ZIM in about 100 places to all call cur() so the system can work.
No need to worry about cursors for drag(), transform(), Blob(), Squiggle(), tap(), etc.
These have all been adjusted to work automatically with F.cursors.
There is a F.cursorList property that is a ZIM Dictionary that keeps track of objects with cursors
When Frame cursors is on, any object with a cursor set that has a matching type will have its CSS cursor turned off
and the object's _cursor property is used to set the F.cursorObj.
If the Frame cursors are turned off, the cursorList is used to reset the CSS cursors on the objects.
Any DisplayObject used for a custom cursor should most-likely be center reg and sized or scaled properly - for instance:
F.cursors = {
default:new Pic("myFinger.png").reg(CENTER).siz(20),
pointer:new Rectangle(10,10,red).reg(CENTER).animate({props:{scale:2}, rewind:true, loop:true})
}
Note that we can animate custom cursors or use an Emitter, etc.
A set of retro cursors is available as F.makeCursors("retro", [optionalTypes]);
So use F.cursors = F.makeCursors("retro");
or F.cursors = {pointer:F.makeCursors("retro", "pointer")};
WARNING: If an object has its level set to the top of the stage in a timeout, interval, call, etc.
then also set the F.cursorObj.top() afterwards so the cursor remains on top.
This has been automatically handled in drag(), transform(), etc.
DRAG SLIDE FRICTION
https://zimjs.com/014/slide.html
BREAK / IMPROVEMENT - added an axis parameter as second parameter to drag() with values of ALL/BOTH or HORIZONTAL or VERTICAL
The boundary can still be set with a value of 0 for either width or height to drag vertically or horizontally with limits
BREAK - the localBounds parameter has been changed to localBoundary
BREAK / IMPROVEMENT - changed all slideDamp to slideFactor with a better sliding equation.
A damping equation was used (slideDamp) but the better equation is just a velocity that decreases by a factor
If the slideFactor is 1 then there is no decrease in velocity - the default is .9 and a value of .6 slows quite quickly.
The velocity is determined by the mouse/finger calculated by the time and distance between 50 milliseconds before release to release.
This change affects drag() with slide:true and also Window() and List().
Thanks Anton Kotenko for the request.
This leads to smoother scrolling lists like most mobile scrolling.
ZIM PHYSICS
https://zimjs.com/014/blobphysics.html
Updated to phsyics_2.2
ZIM Blob() can now recieve addPhysics() but it must be a convex Blob - so no angles less than 90 degrees
This is a limitation of Box2D and can be solved by joining shapes
Added makePoly() method used by addPhysics() for Blob - so there is no need to use makePoly directly.
Fixed drag() and noDrag() to not convert an array of ZIM objects passed in to an array of physics bodies
This is confusing from the outside if using that array for other things.
HIERARCHY - (AND LIST)
https://zimjs.com/014/hierarchy.html
Added new methods to edit the ZIM Hierarchy which can be used to remake associated List() objects
insertBefore(items, id, innerItems) - insert item or an array of items before an id with optional children
this will insert at the same level as the id - also see insertAfter()
can pass in an array for items such as ["TEST", "TEST2"]
can pass in a third parameter for children of a single item
The third parameter can also be an array but if there is a third parameter
and if the first parameter is a list then it only uses the first item in the list
as the parent for the third parameter.
insertAfter(items, id, innerItems) - insert item or an array of items after an id with optional children
this will insert at the same level as the id - also see insertBefore()
can pass in an array for items such as ["TEST", "TEST2"]
can pass in a third parameter for children of a single item
The third parameter can also be an array but if there is a third parameter
and if the first parameter is a list then it only uses the first item in the list
as the parent for the third parameter.
replaceItem(item, id) - replace the current item at the id with the provided item
removeItem(id)...
ZIM 02
NOTE: ZIM has gone through major versions ONE, TWO, TRI, 4TH, VEE, SIX, HEP, OCT, NIO, TEN, CAT, NFT.
We are now on major version ZIM and started with ZIM version ZIM 00.
This is ZIM version ZIM 02. Going forward we will be ZIM 03, ZIM 04, etc.
We can now just start calling the releases ZIM 01, ZIM 02, ZIM 03, etc.
But please note that historically, we have gone through many major releases
with over 8,000 updates and approximately 80,000 lines of code.
ZIM 02
Along with this code release there is also a new ZIM EDITOR at https://zimjs.com/editor
Please see https://zimjs.com/updates.html - rather than repeat updates in two places.
ZIM 01
NOTE: ZIM has gone through major versions ONE, TWO, TRI, 4TH, VEE, SIX, HEP, OCT, NIO, TEN, CAT, NFT.
We are now on major version ZIM and started with ZIM version ZIM 00.
This is ZIM version ZIM 01. Going forward we will be ZIM 02, ZIM 03, etc.
We can now just start calling the releases ZIM 01, ZIM 02, ZIM 03, etc.
But please note that historically, we have gone through many major releases
with over 8,000 updates and approximately 80,000 lines of code.
ZIM 01
Please see https://zimjs.com/updates.html - rather than repeat updates in two places.
ZIM 00
NOTE: ZIM has gone through major versions ONE, TWO, TRI, 4TH, VEE, SIX, HEP, OCT, NIO, TEN, CAT, NFT.
This major release is version ZIM. So we are on ZIM version ZIM 00 - but we are fine calling it ZIM version 00.
Future releases will be ZIM 01, ZIM 02, etc.
As a framework gets more complete, updates and versions slow down - and ZIM is nearing completion.
So it is somewhat ironic referring to ZIM as 00 after nearly 8000 updates on 77,000 lines of code.
ZIM ZIM 00
PIC, VID, AUD, SVG CLASSES
https://zimjs.com/zim/assets.html
The asset process is now wrapped with Pic(), Vid(), Aud() and SVG() classes.
It is still recommended to preload assets in the Frame() or in loadAssets().
asset() will work as always but now there are additional ways to access asset().
The asset system was somewhat inherited from CreateJS to simplify their PreloadJS manifest structure.
In ZIM CAT 00, we introduced auto-loading (lazy-loading) of images and then in ZIM CAT 04 of sounds.
In ZIM ZIM 00, we provide wrappers for these and new video and SVG wrappers too!
HOW IT WORKS
Pic(), Vid(), Aud() and SVG() are ZIM Container objects (except Aud) with types of "Pic", "Vid", "Aud" and "SVG".
** Their parameters use ZIM DUO and ZIM OCT style - the file parameters accept ZIM VEE.
The classes are used as follows:
new Pic(file).center();
new Vid(file).center().play(); // must interact with app first
new Aud(file).play(); // must interact with app first
new SVG(file).center();
Pic() will call asset() and if the asset was preloaded will add the resulting Bitmap to its container.
If the asset was not preloaded, Pic() will lazy-load and transfer the resulting Bitmap to its container.
In both cases, the bitmap (if needed) is available as its bitmap property.
new Pic() will always clone the original asset this will be easier to remember and more intuitive.
Cloning lazy-loaded Pic objects now works without needing to wait for a complete event.
Also, Pic() will provide a "ready" and "complete" event when loaded.
Lazy-loading works with many methods such as center(), centerReg(), scaleTo() and pos()
There are certain things such as Tile() and Scroller() that will warn they need dimensions to be set
Dimesions will be available when preloading using the Frame assets parameter or loadAssets()
or if a width and height is provided to the Pic() parameters
or after the object's "ready" or "complete" event is dispatched.
PATH = "assets/";
new Pic("examples.jpg") // lazy-load the picture from assets/ folder
.scaleTo() // Fill the stage with the picture (more options too)
.center();
Vid() is new and will automatically create and HTML video tag and a source tag (display:none)
and then handle the HTML events and dispatch a "ready" event.
Vid() also wraps the play() and pause() methods and provides duration, currentTime and volume properties
ZIM has also added a keyOut(color, tolerance) - see the CHROMA KEY section.
Note: the app must be interacted with before the video can be played (same as sound).
Vid() has a source property to the HTML video tag and a bitmap property to the ZIM Bitmap.
const video = new Vid("video.mp4")
.cur()
.center();
// init gets called when pane is closed
const pane = new Pane(600,200,"VIDEO ON CANVAS!").show(init);
function init() {
video
.keyOut("#01b03f", .2) // key out the green
.play();
video.on("mousedown", () => {
// note videoPaused property
// not paused (which is for animation)
video.pause(!video.videoPaused);
});
}
Aud() is similar to Pic where it calls asset() which loads from preloaded or lazy-loaded sounds
but default play() parameters have been made available on the main class.
These include file, volume, loop, loopCount, pan, offset, interrupt, maxNum.
Setting a volume of .5 will affect audSound.play() unless a volume is provide in play().
maxNum has been made easier to deal with - it now is a parameter on the Frame(), loadAssets() and asset()
and we provide a parameter right on each Aud() object.
maxNum specifies how many copies of a sound can play at the same time.
interrupt specifies primarily whether to let the first sound play or start it over again.
Sound can only be played after the user interacts with the app.
The result of the play() method works like before to pause the sound, dynamically adjust volume, etc.
and to capture events like complete and loop.
STYLE = {
maxNum:1,
interrupt:"any"
}
const press = new Aud("press.mp3");
circle.on("mousedown", () => {
press.play();
});
SVG() wraps either the existing svgToBitmap() or the SVGContainer() depending on parameters.
An SVG file or a tag can be passed in and will be available as the svg property.
The default svgToBitmap works flawlessly as far as we know but results in a Bitmap.
Basic SVG should work for an SVGContainer, but CSS styles will not (let us know if things are missing).
The advantage of an SVGContainer is that the parts can be transformed or controlled with Beziers.
Note: alternatively, an SVG path can be passed directly to a Blob or Squiggle to:
- 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
Note: SVG can now be lazy-loaded into asset() without preloading - it will become a container with a bitmap inside.
this was added to allow SVG() to work.
const tile = new Tile(new SVG("forest.svg", 130, 100), 2, 1)
.center();
ALERT
It is still optimal to preload in Frame() or loadAssets() first and then use Pic() and Aud().
In doing so, the loading is batched and all dimensions are known before usage.
This avoids double calls to scaling and positioning.
1. ES6 MODULES
https://zimjs.com/es6.html#MODULES
https://zimjs.com/es6/zim_module.html
ZIM has now moved to ES6 Modules as the default way to load ZIM.
The ZIM Crystal scripts have been replaced with modules.
The scripts can still be loaded with conventional script tags:
https://zimjs.com/script.html
The Code page shows modules to start but has a link to toggle to scripts.
The CDN lists ZIM under cdn/00/ - these will increase to cdn/01/, etc.
The module scripts are as follows:
- https://zimjs.org/cdn/00/zim.js
- https://zimjs.org/cdn/00/zim_game.js
- https://zimjs.org/cdn/00/zim_physics.js
- https://zimjs.org/cdn/00/zim_socket.js (must import socket.io in script tag)
- https://zimjs.org/cdn/00/zim_three.js
- https://zimjs.org/cdn/00/zim_cam.js
- https://zimjs.org/cdn/00/zim_pizzazz.js
- https://zimjs.org/cdn/00/zim_test.js (calls docs for readable errors)
These all call ZIM and the latest CreateJS.
There are also the following independent modules:
- https://zimjs.org/cdn/1.3.4/createjs_module.js
- https://zimjs.org/cdn/1.3.4/createjs_doc_module.js
- https://zimjs.org/cdn/00/zim_module.js (CreateJS independent)
Use zns=true in an earlier script tag to force the ZIM namespace
// to use an ES6 module the module file must be on a server
// use a script tag with type=module
// and import the desired module
// Note: this is the only script tag needed
<script type=module>
import zim from "https://zimjs.org/cdn/00/zim";
const frame = new Frame(FIT, 1024, 768, light, dark);
frame.on("ready", ()=>{
const stage = frame.stage;
const stageW = frame.stageW;
const stageH = frame.stageH;
new Circle(100, red).center().drag();
stage.update();
});
</script>
Renamed the Socket file to socket.js (was zimsocket.js)
Made a code page for modules at https://zimjs.com/es6.html
Made a mini-site for modules at https://zimjs.com/es6/zim_module.html
2. PIXEL
https://zimjs.com/zim/pixel.html
https://zimjs.com/zim/pixel2.html
Uses raw canvas processing to pixilate a Display Object.
This is not a pixel by pixel process like the ZIM Effects (BlurEffect, GlowEffect, etc.)
So the speed is very fast.
The Display Object is cached, scaled down and scaled back up with image smoothing disabled.
The scaling procedure is actually faster than scaling with image smoothing turned on.
This effect has been available on the canvas all along, ZIM Pixel makes it easier to use.
// pixelate a Circle
var circle = new Pixel(new Circle(200,red)).center().drag();
// emit pixels
frame.color = darker;
function makePixel() {
return new Pixel(new Circle(40,[pink,blue,purple]),.3)
.alp(.5)
.reg(CENTER);
}
new Emitter({
obj:makePixel,
force:{min:.5, max:2},
gravity:0,
life:3,
shrink:false,
layers:BOTTOM,
animation:{
props:{rotation:[-360, 360]},
time:{min:1,max:10},
ease:"linear",
loop:true
}
}).center();
3. SITE
The ZIM Site has an updated header and footer on all pages.
This header features generative art banner made with ZIM
There is a Dr Abstract signature at the right which links through to a synops.
The synops is a synopsis of Dr Abstract's career of creations
We hope that you enjoy the video - you are welocome to give it a thumbs up on YouTube!
Beneath the banner is a main link bar that is now present on all pages.
This includes the ZIM Docs and Updates pages.
A couple exceptions, ZIM Skool, ZIM Ten, ZIM Cat pages retain the ZIM TEN look.
The Map page has been updated with recent updates.
The Code Page has been updated to the new template with modules.
A toggle link has been added to the template to go to the scripts version.
4. COLOR PICKER SPECTRUM
https://zimjs.com/zim/chromakey.html
The ColorPicker has been redesigned to default to a colors value of "spectrum".
Setting thi...
ZIM NFT 01
A major sub release to ZIM NFT
See examples at https://zimjs.com/nft/bubbling
We have released 12 major versions: ONE, TWO, TRI, 4TH, VEE, SIX, HEP, OCT, NIO, TEN, CAT and NFT.
This is a lot of progress over 7 years. ZIM is one of the largest Canvas frameworks, indeed of any code frameworks.
The goal of our NFT release is to bring more artists on board.
ZIM has a good e-learning and kids app following but it is also built for artists.
We have been making interactive NFTs with ZIM and are seeing more artists in the forums.
Many artists use Processing or P5js and we have extended an invitation to these artists to consider ZIM:
https://medium.com/javascript-in-plain-english/an-invite-for-generative-art-makers-and-interactive-artists-106f3ed186ab
As a framework becomes more stable, major releases slow down.
We have turned to a single digit sub release and slower release cycle.
Generally, we can manage with patches between releases.
This release, the second of the ZIM NFT has two main updates the cam helper module and the Dialog class in the game module.
There are also a number of exciting important additions to the main zim file as shown below.
About half of these come from requests in the forums so many thanks for the suggestions.
It is nice to see these changes in our https://zimjs.com/updates.html page
where we format them and add code examples.
Please join us at https://zimjs.com/slack and https://zimjs.com/discord
where we have community and support.
Here are the new features in ZIM NFT 01
DIALOG
https://zimjs.com/nft/bubbling/dialog.html
Added a Dialog() class to ZIM Game helper library.
This makes speech bubbles or boxes with text and arrows.
Updated GAME MODULE to game_2.6.js
ZIM CAM
https://zimjs.com/cam
Added a cam.js helper module (like socket, game, physics, three, pizzazz, etc.)
This has Cam, CamMotion, CamCursor, CamAlpha and CamControls classes
to capture cam screenshots, add effects or a cursor at cam motion.
This is a recreation of the Ostrich Library made in Flash in 2009 by Dr Abstract (Dan Zen).
It has been planned to bring into ZIM since ZIM ONE! Yay, it is here and works well.
EMOJI
https://zimjs.com/nft/bubbling/emoji.html
https://zimjs.com/emoji
Added a ZIM Emoji class that extends a Label to show an emoji.
This could be done with a plain Label but the Emoji class makes it more apparent.
Also added a ZIM EmojiPicker to allow users to pick an emoji and make an Emoji object.
For coding, the ZIM Emoji tool is provided to get UTF strings for emojis to add to code.
Added a unicodeToUTF() function under the CODE Module to support conversions for Emoji and EmojiPicker
Thanks Karel Rosseel and Chris Spolton for the guidance.
ZIM CRYSTAL UPDATES
https://zimjs.com/crystal.html
Added crystals for ZIM NFT 01
and new crystal formats: zim_cam.js to add the new cam.js library
and zim_pizzazz.js - this adds pizzazz_01, 02 and 03 for backings, icons and patterns
BLENDMODES
https://zimjs.com/nft/bubbling/variety.html
Added a helper method called blendmodes() that cycles through the blendmodes - ble() - on an object
Click the object to toggle the cycling
ODDS
https://zimjs.com/nft/bubbling/variety.html
Added an odds(percent) function to the Code section.
This is the same as rand() < percent/100 but a little easier to understand
if (odds(20)) new Emitter().center(); // add an emitter 20% of the time
SEEDRANDOM
https://zimjs.com/nft/bubbling/variety.html
Seed the Math.random() and therefore ZIM rand() and ZIM VEE values using rand()
This allows you to repeat the random numbers for the same seed.
Handy for making specific random art, or game levels, etc.
This is the main feature of FXHash where you can find captured generative art and scenes:
Here is a Dr Abstract collectible example https://www.fxhash.xyz/generative/5810
QR
https://zimjs.com/nft/bubbling/variety.html
Added a QR Code helper - must import https://zimjs.org/cdn/qrcode.js
This is a library by David Shim at https://github.com/davidshimjs/qrcodejs
The ZIM Class makes a ZIM Bitmap of the QR Code - thanks Bart Libert for the suggestion
DIR
https://zimjs.com/nft/bubbling/variety.html
Set a global DIR constant to either "ltr" or "rtl"
Use along with START and END constants
for pos(), reg(), Label(), LabelLetters(), and List()
START for horizontal position or align will be "left" if DIR is "ltr" and "right" if DIR is "rtl"
END for horizontal position or align will be "right" if DIR is "ltr" and "left" if DIR is "rtl"
Thanks Marva for the idea and Xuntar for the confirm.
REG
https://zimjs.com/nft/bubbling/variety.html
Added LEFT, RIGHT, CENTER, TOP, CENTER, BOTTOM and START, END to reg()
Thanks Karel Rosseel for the request!
STYLE ONCE
https://zimjs.com/nft/bubbling/variety.html
Added a once property to STYLE
Set this to true to run the STYLE setting only once.
Once will delete the STYLE after the next object is made
regardless of the whether the style is applied.
STYLE = {color:red, once:true}
new Circle().center(); // this will be red
new Circle().center().mov(20); // this will be black
Set a once property to a type such as "Label" and the STYLE will be cleared after a label has been made
Note: some objects like an Arrow is made from a Button which has a Label so this sometimes can be tricky.
If it does not work, just turn the STYLE = {} or Style.clear() manually.
CONVERTCOLOR UPDATES
Adjusted the convertColor to handle 8 (and 4) character hex numbers - thanks Ami Hanja for the suggestion
where the alpha is on the right side.
Passing in an alpha parameter (or RGBA as color) and HEX as output will add alpha on the end of the hex
TILT
Added device motion and orientation docs entry to the Frame module (thanks Karel Rosseel)
This is similar to adding Image, Sound and Font to the Frame module
It just helps the topic be found in the docs - even though it is already described in Frame
FRAME TAB FOCUS/BLUR
Frame now has "tabfocus" and "tabblur" events for when tab is hidden
This is not focus on the page but rather the tab.
INDICATOR UPDATES
https://zimjs.com/nft/bubbling/indicator.html
Added Emoji support to Indicator indicatorType - add an Emoji and it will show them
also added backgroundAlpha as parameter for setting unselected Emoji alpha.
Added heart and star to the indicatorType of a ZIM Indicator() - thanks Karel Rosseel for suggestion
Combine these with interactive:true parameter to get an easy rating scale
Adjusted Indicator to toggle off and on last light so can set to zero lights
COLLAPSE
https://zimjs.com/nft/bubbling/collapse.html
Window, List and Panel now have collapse, collapseColor and collapsed parameters - thanks Karel Rosseel for the request
Also collapseIcon and collapsed properties as well as a collapse(state) method.
BREAK - changed the name of the close icon and fullScreen icon to closeIcon and fullScreenIcon for Window
and added a fullScreen(state) method to Window
PANEL UPDATES
With the addition of the collapse button the Panel parameters have been rearranged to:
corner, close, closeColor, next, nextColor, extraButton, collapse, collapseColor, collapsed, align
and the arrow parameter has been called next and a nextColor added.
Added a content container and add(object, center, replace) method to Panel to help collapsed content be hidden
So this is like Window() where content can be added with add() method - and removed with removeFrom()
WINDOW UPDATES
In addition to the collapse functionality,
also added adjusted add(object, center, replace) to Window BREAK
Added the following events to Window
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
GENERAL
Fixed Emitter on text - was flashing due to placement of alpha IMPROVEMENT
Adjusted ZIM Label in labelWidth + labelHeight mode so shiftHorizontal and shiftVertical happens once
Fixed when toggling a button the text color is now returning to rollColor
Made scramble() method return the scrambler object so we can chain it.
Cloning DisplayObjects were set with the following for cloning bounds:
if ((!this.type || this.type=="Shape" || this.type=="Blob" || this.type=="Squiggle") && this._bounds) // clone the bounds
We are not sure why this limitation - there was probably a reason... but we now think all DisplayObjects should have bounds cloned
So are adjust this accordingly.
Added stickThickness parameter to Blob and Squiggle.
Added the borderWidth to titleBar of Window - seemed to be off otherwise.
Fixed lineOrientation glitch in ZIM Connectors - thanks @chu4ng on GitHub issue.
Added an AVE constant to represent average - and has a value of "ave" (not "average")
Made a lazy loading asset be queueOnly loading so it does not trigger the Frame complete event
as they each have their own complete event.
PATCHES
There were 90 lines of patches for ZIM NFT 00 - these of course are all in ZIM NFT 01.
ZIM SHIM
Reorganized ZIM SHIM folder to have just the basic example (zim) in the main folder
and four other examples in folders: (thanks Paul Ruda for the inspiration)
data - an example of loading comma delimited file into Animate with ZIM
full - like the basic example but with full screen with scaling
physics - a physics example
local - a version with CreateJS and ZIM files locally in the directory
DOCS
Added individual doc pages for each entry - thanks ZIMsters for the suggestion
ZIM NFT
ZIM NFT (the next major version after ZIM CAT and ZIM TEN) features:
1. INTERACTIVE NFTS https://zimjs.com/nft NFTs (Non-Fungible Tokens) are a lastest craze for Artists and Collectors with some like Beeple and CryptoPunks selling for millions! ZIM NFT is actually an NFT that you can collect if you are quick enough. At the bottom of the page linked above we tell you how to collect the ZIM NFT. ZIM can be used to make interactive NFTs to sell as art on Web apps such as hic et nunc https://hicetnunc.xyz Please see the NFT page for more! https://zimjs.com/nft Incuding a guide to making NFTs, setting up a Wallet and COLLECTING the ZIM NFT! https://www.youtube.com/watch?v=brIWbJ8QYO8 https://www.youtube.com/watch?v=gwMdtCT3Kbo
2. ZIM CRYSTAL - IMPROVEMENT https://zimjs.com/crystal We now present seven single files that can be used to load ZIM Crystals. zim.js // a crystal of createjs.js, zim_min.js zim_game.js // a crystal of createjs.js, zim_min.js, game.js zim_physics.js // a crystal of createjs.js, zim_min.js, box2d.js, physics.js, game.js zim_three.js // a crystal of createjs.js, zim_min.js, three.min.js, orbitControls.js, three.js zim_socket.js // a crystal of createjs.js, zim_min.js, socketio.js, socket.js, zimserver_urls.js zim_distill.js // a crystal of createjs.js, a distilled.js placeholder URL zim_test.js // a crystal of createjs.js, zim_doc.js <script src=https://zimjs.com/cdn/nft/00/zim.js></script><!-- will load ZIM and CreateJS -->
3. TEXTINPUT - IMPROVEMENT https://zimjs.com/explore/textinput.html The ZIM TextInput() class provides editable text on the Canvas. Three cheers for Cajoek who created a LabelInput that mirrors an HTML input field. We then wrapped this in a Window to provide a scrollable TextInput box. Now input text is a proper part of the canvas - as opposed to an overlay like ZIM TextArea. It is a proper DisplayObject that extends from a ZIM Window and has a ZIM Label. There is a blinker which is a ZIM Rectangle and all this can be rotated, layered, etc. For this release, the TextInput is one line and behaves very much like an HTML input of type text. See the docs for more features https://zimjs.com/docs.html?item=TextInput
4. NEW SQUIGGLE AND BLOB EDITS - IMPROVEMENT https://zimjs.com/explore/pathediting.html Added the following functions to the code module to help cut up, join, reverse and trim paths. These are also available as methods on the Squiggle and Blob (availability depends on relevance). reversePoints(points) Reverses Squiggle formatted points appendPoints(original, points, controlType) Adds a set of Squiggle points to after an original set of Squiggle points The joining point is merged with the provided optional controlType ** appendPoints() expects the first point on points (the second parameter) to be at the last point of the original (the first parameter) prependPoints(original, points, controlType) Adds a set of Squiggle points to before an original set of Squiggle points The joining point is merged with the provided optional controlType ** prependPoints() expects the last point on points (the second parameter) to be at the first point of the original (the first parameter) splitPoints(points, index, trimEnds) Splits Squiggle points into two sets of Squiggle points Also used by Squiggle splitPoints() and Blob makeSquiggle() trimEndPoints(points) Take outside Bezier rectangles off end points of Squiggle Modifies the points but then will have to make Squiggle from modified points Used internally, but might want to create a Squiggle from half the points or every other point this function would make sure ends are clean. SQUIGGLE: gets reversePoints(), appendPoints(), prependPoints(), splitPoints(), and 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) BLOB: gets eversePoints() and 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
5. SCALETO - BREAK ZIM scaleTo() now defaults to FILL if no percentages are provided. This is so we can easily set backgrounds that fill the stage: backing.scaleTo().center(); // will now FILL the stage // we no longer have to use backing.scaleTo({type:FILL}).center(); // to FIT 100% to the stage use: obj.scaleTo({type:FIT}).center(); // note that the default if a percentage is applied is FIT obj.scaleTo(stage,80,80).center(); // so this would also FIT to the stage 100% obj.scaleTo(stage,100,100).center();
6. GENERAL Added countDecimals(num) to Code module - to count decimals in number. Added backgroundColor property to Window Changed Circle percent property (not parameter) to percentage BREAK to not conflict with animate() percent Added blendMode:"difference", etc. to STYLE as part of the transformations Added a "closing" event to Pane that triggers before the stage update of the closed Pane this provides for reloading the page without closing the pane which might cause a flash The pane now closes and dispatches the "close" event 10ms after being pressed. Adjusted Frame to wait for its width and height to be >= 1 before triggering a ready event This came up on hic et nunc which shows NFTs in a React component IMPROVEMENT it seemed to start with a width and height of 0 when loading from cache.
7. PATCHES Note that there were 77 patches to ZIM Cat 04 - all of which have improved ZIM NFT.
8. ZIM HELPER MODULES ZIM game module has been updated to 2.5 the registration point on the Scorer and Timer for isometric RIGHT has been set to the center (thanks Karel Rosseel) Patched ZIM physics_2.2.js to make gravity a get/set property - was just a get property.
9. ZIM DOCS - IMPROVEMENT Added link to EXPAND button so specific docs link can be copied with right click or long click on mobile (thanks Karel Rosseel) Updated dozens of docs examples to latest ZIM practice Thanks Karel Rosseel for close to 50 refinements -if anyone else sees things, please report. Added examples and descriptions for Pizzazz 4 - paths Added search proxies - so searching visible will find vis, etc. { visible:"vis", blendmode:"ble", registration:"reg", registrationPoint:"reg", shadow:"sha", name:"nam", alpha:"alp", rotation:"rot", scale:"sca", scaleX:"sca", scaleY:"sca", x:"loc", y:"loc", skew:"ske", skewX:"ske", skewY:"ske", width:"siz", height:"siz", cursor:"cur", asset:"images", picture:"images", assets:"images", pictures:"images" };Added base methods to ZIM Docs - these are mostly CreateJS DisplayObject methods
cache(), updateCache(), uncache(), on(), off(), removeAllEventListeners(), getBounds(), setBounds(), clone(), dispose()
Added filter for Docs search to ignore text inside wrong answers when they come first
for instance, searching for ble for blendMode would find Scrambler first - now it does not
If YOU find a wrong answer like this, please let us know and we can add it to the filter
Make sure you are at the TOP when you do your search. Cheers.
Added videos links for:
CAT: "Book", "effect", "updateEffects", "noEffect", "BlurEffect", "GlowEffect", "ShadowEffect",
"ColorEffect", "MultiEffect", "AlphaEffect", "zimEase", "zimEase"
HELPER: "PIZZAZZ 4 makePath"
10. ZIM SITE - IMPROVEMENT Added 40 examples to Examples including Feature, NFTS (new!), Collection, CodePen and Magical. Updated the NEWS and ABOUT to ZIM NFT Added NFT and Crystal pages and links on the CODE page. Added TIPS to top of Bits View Code pages - and changed copyright to ZIM (left 2016 as that is when they were made) Changed the faveicon to latest ZIM icon stem.
11. ZIM KIDS - IMPROVEMENT Made major updates to ZIM Kids Slate editor. Thanks Karel Rosseel for the prompting. Added over 600 Backing, Nature, People and Things images and Sounds These can be checkmarked and then automatically used in slate as asset("name") Included a six level expandable help section to describe how to use assets. Added STORE functionality to store code while trying other code then retreive the code. Organized and provide DEMO code for Slate. Added Physics option to SLATE and sounds to the as...