Can anyone help me convert this paperscript to javascript? - javascript

I have this paperscript from paper.js and i would like it to be converted in javascript but i cant get the mouse drag to work.
PaperScript recognises a couple of special event handlers when they are declared as global functions, while in JavaScript, these need to be manually installed on the appropriate object.
Codepen of the paperscript
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-full.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<script type="text/paperscript" canvas="myCanvas">
var rectangle = new Rectangle(new Point(50, 50), new Point(150, 100));
var path = new Path.Rectangle(rectangle);
path.fillColor = '#e9e9ff';
path.strokeColor = 'black';
path.strokeWidth = 2;
path.selected = true;
path.closed = true;
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 8
};
var segment, path;
var movePath = false;
function onMouseDown(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
};
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
} else if (hitResult.type == 'stroke') {
var location = hitResult.location;
segment = path.insert(location.index + 1, event.point);
//path.smooth();
}
}
movePath = hitResult.type == 'fill';
if (movePath)
project.activeLayer.addChild(hitResult.item);
}
function onMouseMove(event) {
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
}
function onMouseDrag(event) {
if (segment) {
segment.point += event.delta;
//path.smooth();
} else if (path) {
path.position += event.delta;
}
}
</script>
<canvas id="myCanvas" resize></canvas>
Thank you in advance!

Differences between PaperScript and JavaScript contexts are detailled here.
In order to make the less changes possible to your code, you have to:
Install Paper.js in global scope. This allow you to use classes like Path, Point, ... directly (without passing trough global paper object).
Setup Paper.js to use your canvas. This is equivalent to setting the PaperScript canvas attribute.
Create a Tool instance that you will use to register your event handlers.
Use math operator functions (like Point.add()) instead of operators (like +) when manipulating points.
Here is your code working in JavaScript context.
// expose paperjs classes into global scope
paper.install(window);
// bind paper to the canvas
paper.setup('canvas');
var rectangle = new Rectangle(new Point(50, 50), new Point(150, 100));
var path = new Path.Rectangle(rectangle);
path.fillColor = '#e9e9ff';
path.strokeColor = 'black';
path.strokeWidth = 2;
path.selected = true;
path.closed = true;
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 8
};
var segment, path;
var movePath = false;
// create a custom tool
var customTool = new Tool();
// attach handlers to the tool
customTool.onMouseDown = function(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult) {
return;
}
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
}
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
} else if (hitResult.type == 'stroke') {
var location = hitResult.location;
segment = path.insert(location.index + 1, event.point);
//path.smooth();
}
}
movePath = hitResult.type == 'fill';
if (movePath) {
project.activeLayer.addChild(hitResult.item);
}
};
customTool.onMouseMove = function(event) {
project.activeLayer.selected = false;
if (event.item) {
event.item.selected = true;
}
};
customTool.onMouseDrag = function(event) {
if (segment) {
// use methods instead of operators
segment.point = segment.point.add(event.delta);
//path.smooth();
} else if (path) {
path.position = path.position.add(event.delta);
}
};
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
canvas[resize] {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.min.js"></script>
<canvas id="canvas" resize></canvas>

Related

4 animated SVGs in one HTML file using Animate CC

http://christianluneborg.com/dev/animation/icon-global.html
How do I load 4 separated animated SVGs in one JS/HTML files exported from Animate CC? I have created 1 animated SVG and it exports 3 different JS in one HTML. Is there a way I can reuse JS for other 3 icon SVGs without messing up the code? I know its not a good practice to load a bunch of JS files for each animated SVGs.
Just for 1 animated SVG (JS)
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="icon-skyscrapers.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container,
fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp=AdobeAn.getComposition("C1F9C7BD5BEEC941A1FE079EA94C1BF3");
var lib=comp.getLibrary();
handleComplete({},comp);
}
function handleComplete(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
exportRoot = new lib.iconskyscrapers();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage)
stage.addEventListener("tick", handleTick)
function getProjectionMatrix(totalDepth) {
var focalLength = 528.25;
var projectionCenter = { x : lib.properties.width/2, y : lib.properties.height/2 };
var scale = (totalDepth + focalLength)/focalLength;
var scaleMat = new createjs.Matrix2D;
scaleMat.a = 1/scale;
scaleMat.d = 1/scale;
var projMat = new createjs.Matrix2D;
projMat.tx = -projectionCenter.x;
projMat.ty = -projectionCenter.y;
projMat = projMat.prependMatrix(scaleMat);
projMat.tx += projectionCenter.x;
projMat.ty += projectionCenter.y;
return projMat;
}
function handleTick(event) {
var focalLength = 528.25;
var cameraInstance = exportRoot.___camera___instance;
if(cameraInstance !== undefined && cameraInstance.pinToObject !== undefined)
{
cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
if(cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !== undefined)
cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
}
for(child in exportRoot.children)
{
var layerObj = exportRoot.children[child];
if(layerObj == cameraInstance)
continue;
if(layerObj.currentFrame != layerObj.parent.currentFrame)
{
layerObj.gotoAndPlay(layerObj.parent.currentFrame);
}
var matToApply = new createjs.Matrix2D;
var cameraMat = new createjs.Matrix2D;
var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
var cameraDepth = 0;
if(cameraInstance && !layerObj.isAttachedToCamera)
{
var stageCenter = { 'x' : lib.properties.width/2, 'y' : lib.properties.height/2 };
var mat = cameraInstance.getMatrix();
mat.tx -= stageCenter.x;
mat.ty -= stageCenter.y;
cameraMat = mat.invert();
cameraMat.prependTransform(stageCenter.x, stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
cameraMat.appendTransform(-stageCenter.x, -stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
if(cameraInstance.depth)
cameraDepth = cameraInstance.depth;
}
if(layerObj.depth)
{
totalDepth = layerObj.depth;
}
//Offset by camera depth
totalDepth -= cameraDepth;
if(totalDepth < -focalLength)
{
matToApply.a = 0;
matToApply.d = 0;
}
else
{
if(layerObj.layerDepth)
{
var sizeLockedMat = getProjectionMatrix(layerObj.layerDepth);
if(sizeLockedMat)
{
sizeLockedMat.invert();
matToApply.prependMatrix(sizeLockedMat);
}
}
matToApply.prependMatrix(cameraMat);
var projMat = getProjectionMatrix(totalDepth);
if(projMat)
{
matToApply.prependMatrix(projMat);
}
}
layerObj.transformMatrix = matToApply;
}
}
}
//Code to support hidpi screens and responsive scaling.
function makeResponsive(isResp, respDim, isScale, scaleType) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
canvas.width = w*pRatio*sRatio;
canvas.height = h*pRatio*sRatio;
canvas.style.width = dom_overlay_container.style.width = anim_container.style.width = w*sRatio+'px';
canvas.style.height = anim_container.style.height = dom_overlay_container.style.height = h*sRatio+'px';
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
makeResponsive(false,'both',false,1);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
HTML
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:113px; height:84px">
<canvas id="canvas" width="113" height="84" style="position: absolute; display: block; background-color:rgba(255, 255, 255, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:113px; height:84px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>

Phaser Tiled tilemap layers not colliding with player

I've been working on a Phaser game for a project at university. All of this is relatively new stuff to me, so I'm learning on the fly. I've managed to create a simple tilemap using Tiled, and got it to import to Phaser sucessfully. However, I can't make the player collide with the 'platform' layer, and I've tried just about everything I can find online.
I've cut down my game code to just what's needed for you to (hopefully) point out my error, but it all runs without errors usually. I can also upload any JSON or Image files that might be needed.
var SuddenGame = SuddenGame || {};
var char;
var map;
// GAMEPLAY STATE //
SuddenGame.playState = function() {};
SuddenGame.playState.prototype = {
init: function() {
this.game.renderer.renderSession.roundPixels = true;
},
create: function() {
//Setup FPS Counter
this.game.time.advancedTiming = true;
//Stop game from pausing if a player tabs out
this.stage.disableVisibilityChange = true;
//Import and play background music
music = this.game.add.audio('menumusic');
music.play('', 0, 1, true);
//Create Dotted Background
this.background = this.game.add.tileSprite(0,
this.game.height - this.game.cache.getImage('background').height,
this.game.width,
this.game.cache.getImage('background').height,
'background'
);
this.dots = this.game.add.tileSprite(0,
this.game.height - this.game.cache.getImage('dots').height,
this.game.width,
this.game.cache.getImage('dots').height,
'dots'
);
//Enable Physics Engine
this.game.physics.startSystem(Phaser.Physics.ARCADE);
//Add level one tilemap
map = this.game.add.tilemap('levelone');
map.addTilesetImage('scifi_platformTiles_32x32', 'scifi_platformTiles_32x32');
backgroundTiles = map.createLayer('backgroundLayer');
Objective = map.createLayer('Objective');
Platform = map.createLayer('Platform');
this.game.add.existing(Platform);
this.physics.arcade.enable(Platform);
map.setCollisionBetween(1, 1000, true, 'Platform');
Platform.resizeWorld();
Platform.debug = true;
this.char = this.add.sprite(50, 470, 'hero');
this.physics.arcade.enable(this.char);
this.char.body.gravity.y = 1300;
this.char.body.collideWorldBounds = true;
this.char.scale.setTo(2, 2);
//Create Player Animations
var idle = this.char.animations.add('idle', [0]);
var walk = this.char.animations.add('walk', [0, 1, 2, 1]);
this.game.camera.follow(this.char);
},
update: function() {
this.game.physics.arcade.collide(char, Platform);
this.physics.arcade.TILE_BIAS = 40;
if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT) && !this.char.body.touching.left) {
this.char.body.velocity.x = -150;
this.char.animations.play('backwalk', 10, true);
} else if (this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) && !this.char.body.touching.right) {
this.char.body.velocity.x = 150;
this.char.animations.play('walk', 10, true);
} else if (this.game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
this.char.animations.play('die', 10, true);
} else {
this.char.body.velocity.x = 0;
this.char.animations.play('idle', 7, true);
}
if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && this.game.time.now > jumpTimer) {
{
this.char.animations.play('jump', 10);
this.char.body.velocity.y = -1000;
jumpTimer = this.game.time.now + 750;
}
}
//if (this.cursors.up.isDown && !this.char.body.touching.down ) {
if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT) && this.char.body.touching.left && this.game.time.now > jumpTimer) {
this.char.body.velocity.y = -500;
jumpTimer = this.game.time.now + 1;
}
if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) && this.char.body.touching.right) {
this.char.body.velocity.y = -500;
this.char.body.velocity.x = -2500;
//jumpTimer = this.game.time.now + 1;
}
//More update code here
},
render: function() {
this.game.debug.text(this.game.time.fps || '--', 2, 14, "#00ff00");
}
}
Apologies if I've missed an extremely obvious mistake, I'm pretty sleep deprived right now!

Paper.js - convert `paperscript` to `javascript`

I am trying to change this paperscript:
<script type="text/paperscript" canvas="canvas-1">
tool.minDistance = 10;
tool.maxDistance = 45;
var path;
function onMouseDown(event) {
path = new Path();
path.fillColor = new Color({ hue: Math.random() * 360, saturation: 1, brightness: 1 });
path.add(event.point);
}
function onMouseDrag(event) {
var step = event.delta / 2;
step.angle += 90;
var top = event.middlePoint + step;
var bottom = event.middlePoint - step;
path.add(top);
path.insert(0, bottom);
path.smooth();
}
function onMouseUp(event) {
path.add(event.point);
path.closed = true;
path.smooth();
}
</script>
to a stand alone javascript like:
paper.install(window);
window.onload = function() {
paper.setup('myCanvas');
tool.minDistance = 10;
tool.maxDistance = 45;
var path;
function onMouseDown(event) {
path = new Path();
path.fillColor = {
hue: Math.random() * 360,
saturation: 1,
brightness: 1
};
path.add(event.point);
}
function onMouseDrag(event) {
var step = event.delta / 2;
step.angle += 90;
var top = event.middlePoint + step;
var bottom = event.middlePoint - step;
path.add(top);
path.insert(0, bottom);
path.smooth();
}
function onMouseUp(event) {
path.add(event.point);
path.closed = true;
path.smooth();
}
}
it give me an error:
TypeError: undefined is not an object (evaluating 'tool.minDistance =
10')
What is tool here? I understand that I might need to declare it before I can use it. Any idea how to resolve this?
You need to make the global scope as outlined in the documentation :
paper.install(window);
Then get on with global defs. :
window.onload = function() {
// Get a reference to the canvas object
paper.setup('myCanvas');
// In your case create tools
var tool = new Tool();
tool.minDistance = 10;
tool.maxDistance = 45;
Then continue as usual, this will set up your tools.. More can be found here.
Incidentally you've actually already done this correctly for Path(), so the same applies to Tool()
When I use Paper.js directly in javascript I prefer to create paper object this way:
var canvas = document.getElementById('canvas-line');
paper.setup(canvas);
// and then if you want to create some Paper.js object prefix it's name with paper
var myPath = new paper.Path();
If you want to use tool you need to decelerate it with new paper.Tool();
For example if you want to check whether path was clicked:
var tool1 = new paper.Tool();
var handle;
var myPath;
myPath.fullySelected = true;
tool1.onMouseDown = function(event) {
handle = null;
// Do a hit test on path for handles:
var hitResult = myPath.hitTest(event.point, {
handles: true,
fill: true,
stroke: true,
segments: true,
tolerance: 2
});
if (hitResult) {
if (hitResult.type == 'handle-in') {
handle = hitResult.segment.handleIn;
} else if (hitResult.type == 'segment') {
handle = hitResult.segment.point;
} else if (hitResult.type == 'handle-out') {
handle = hitResult.segment.handleOut;
}
}
}
You can find more informations about tools in here http://paperjs.org/reference/tool/

Moving mesh on the screen without being in torn animation

var leftf;
var rightf;
$(document).keyup(function() {
clearInterval(leftf);
clearInterval(rightf);
});
$(document).keydown(function (e) {
if (e.which == 37) {
// Left Arrow Pushed
leftf=setInterval(function(){
meshes[0].rotation.y=Math.PI/4;
if(meshes[0].position.x>-3.5)meshes[0].position.x-=0.1;
console.log(meshes[0].position.x);
},1000/engine.getFps());
} else if (e.which == 39) {
// Right Arrow Pushed
meshes[0].rotation.y=3*Math.PI/4;
//meshes[0].translate(BABYLON.Axis.X, Math.sin(v), BABYLON.Space.WORLD);
rightf=setInterval(function(){
meshes[0].position.x+=0.1;
},1000/engine.getFps());
}
});
Can you please tell me why this is not working in the browser although it is in my opinion the right way of moving the mesh on the screen without being torn (torn animation)?
It starts moving the mesh correctly but after a while the mesh is flying around without the logic. Is setting and clearing the Interval such a problem for the browsers?
Thank you.
Now it is running, perhaps I have a solution:
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Babylon.js sample code keyboard arrows</title>
<!-- Babylon.js -->
<script src="index_subory/hand.js"></script>
<script src="index_subory/cannon.js"></script>
<script src="index_subory/oimo.js"></script>
<script src="index_subory/babylon.2.0.debug.js"></script>
<script src="index_subory/jquery.min.js"></script>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<div id="idecko" style="background-color:grey;color:white;font-weight:bold;margin-left:auto;margin-right:auto;text-align:center;">text </div>
<canvas height="782" width="1440" id="renderCanvas"></canvas>
<script>
var canvass = $('#renderCanvas');
// check to see if we can do webgl
// ALERT FOR JQUERY PEEPS: canvas is a jquery obj - access the dom obj at canvas[0]
var dcanvas = canvass[0];
expmt = false;
if ("WebGLRenderingContext" in window) {
//alert("browser at least knows what webgl is.");
}
// some browsers don't have a .getContext for canvas...
try {
gl = dcanvas.getContext("webgl");
}catch (x){
gl = null;
}
if (gl == null) {
try {
gl = dcanvas.getContext("experimental-webgl");
}catch (x){
gl = null;
}
if (gl == null) {
//console.log('but can\'t speak it');
}else {
expmt = true; //alert('webgl experimentally.');
}
} else {
//alert('webgl natively');
}
if (gl || expmt) {
//alert("loading webgl content.");
} else {
alert("CHYBA: Váš prehliadač nepodporuje WebGL, ľutujeme. (ERROR: Your browser does not support WebGL, sorry.)");
canvas.remove();
}
if (BABYLON.Engine.isSupported()) {
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
// Skybox
var skybox = BABYLON.Mesh.CreateBox("skyBox", 800.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("index_subory/skybox/cubemap", scene);
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skybox.material = skyboxMaterial;
//var sphere = BABYLON.Mesh.CreateSphere("sphere", 1.0, 1.0, scene);
var createScene = function () {
// setup environment
var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 10,80), scene);
var camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 0, -5), scene);
var light2 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(10, 10, -80), scene);
var turnLeft = false; var turnRight = false;
var accelerate = false; var breaking = false;
BABYLON.SceneLoader.ImportMesh("Cube.001", "index_subory/", "jet2b.babylon", scene,function(meshes){
meshes[0].position.x = Math.round((Math.random() * 1) + 0);
meshes[0].position.y = Math.round((Math.random() * 1) + 0);
var speed = 0;
scene.registerBeforeRender(function() {
if (scene.isReady()) {
camera.target = sphere.position;
speed=0.02;
if (turnRight) {
meshes[0].rotation.y=3*Math.PI/4;
meshes[0].position.x += speed;
}
if (turnLeft) {
meshes[0].rotation.y=Math.PI/4;
meshes[0].position.x -= speed;
}
if (breaking) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y -= speed;
}
if (accelerate) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y += speed;
}
}
});
var sphere = BABYLON.Mesh.CreateSphere("sphere", 0.5, 0.5, scene);
var simpleMaterial = new BABYLON.StandardMaterial("texture2", scene);
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
var myVar2;
function myFunction2() {
myVar = setInterval(function(){
//sphere.translate(BABYLON.Axis.Z, -0.1, BABYLON.Space.WORLD);
sphere.position.z-=0.1;
var delta=0.2;
if(Math.abs(Math.round(meshes[0].position.x-sphere.position.x))<=delta&&Math.abs(Math.round(meshes[0].position.y-sphere.position.y))<=delta&&Math.abs(Math.round(meshes[0].position.z-sphere.position.z))<=delta){
$('#idecko').html('<span style=\'background-color:yellow;color:red;\'>BANG! Červeného trpaslíka trafila zelená planéta! (Red dwarf shot by green planet!)</span>');
//$('#idecko').append("<embed src='index_subory/explosion.mp3' hidden=true autostart=true loop=false>");
if(navigator.userAgent.indexOf("Trident")==-1)var audio = new Audio('index_subory/explosion.mp3');
if(navigator.userAgent.indexOf("Trident")!=-1)var audio = new Audio('index_subory/explosion.wav');
audio.loop = false;
audio.play();
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 0, 1);//Green
sphere.material=simpleMaterial;
}else{
$('#idecko').html('<span style=\'background-color:grey;color:white;\'>Unikaj červený trpaslík (šípky na klávesnici)! (Run away red dwarf (keyboard arrows)!)</span>');
}
if(sphere.position.z<-5){
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
}
}, 50);
}
function myStopFunction2() {
clearTimeout(myVar2);
}
myFunction2();
$(document).keyup(function (evt) {
if (evt.keyCode == 37 || evt.keyCode == 39) {
turnLeft = false;
turnRight = false;
}
if (evt.keyCode == 38 || evt.keyCode == 40) {
accelerate = false;
breaking = false;
}
});
$(document).keydown(function (evt) {
if (!scene)
return;
//console.log(evt.keyCode);
if (evt.keyCode == 32) {
}
//Key LEFT
if (evt.keyCode == 37) {
turnLeft = true;
turnRight = false;
}
//Key RIGHT
if (evt.keyCode == 39) {
turnLeft = false;
turnRight = true;
}
//Key UP
if (evt.keyCode == 38) {
accelerate = true;
breaking = false;
}
//Key BACK
if (evt.keyCode == 40) {
breaking = true;
accelerate = false;
}
});
});
return scene;
}
var scene = createScene();
var assetsManager = new BABYLON.AssetsManager(scene);
//var meshTask = assetsManager.addMeshTask("jet2 task", "", "./index_subory/", "jet2.babylon");
var textTask0 = assetsManager.addTextFileTask("text task0", "./index_subory/jet2b.babylon");
var textTask1 = assetsManager.addTextFileTask("text task1", "./index_subory/hand.js");
var textTask2 = assetsManager.addTextFileTask("text task2", "./index_subory/cannon.js");
var textTask3 = assetsManager.addTextFileTask("text task3", "./index_subory/oimo.js");
var textTask4 = assetsManager.addTextFileTask("text task4", "./index_subory/babylon.2.0.debug.js");
var textTask5 = assetsManager.addTextFileTask("text task5", "./index_subory/jquery.min.js");
var binaryTask1 = assetsManager.addBinaryFileTask("binary task 1", "./index_subory/explosion.mp3");
var binaryTask2 = assetsManager.addBinaryFileTask("binary task 2", "./index_subory/explosion.wav");
var binaryTask3 = assetsManager.addBinaryFileTask("binary task 3", "./index_subory/skybox/cubemap_nx.jpg");
var binaryTask4 = assetsManager.addBinaryFileTask("binary task 4", "./index_subory/skybox/cubemap_ny.jpg");
var binaryTask5 = assetsManager.addBinaryFileTask("binary task 5", "./index_subory/skybox/cubemap_nz.jpg");
var binaryTask6 = assetsManager.addBinaryFileTask("binary task 6", "./index_subory/skybox/cubemap_px.jpg");
var binaryTask7 = assetsManager.addBinaryFileTask("binary task 7", "./index_subory/skybox/cubemap_py.jpg");
var binaryTask8 = assetsManager.addBinaryFileTask("binary task 8", "./index_subory/skybox/cubemap_pz.jpg");
//engine.displayLoadingUI();
engine.loadingUIText = "Loading... (Načítavanie...)";
assetsManager.onTaskSuccess = function (task) {
// Do something with task.data.
//engine.hideLoadingUI();
};
assetsManager.onTaskError = function (task) {
// Do something with task.data.
alert('Error with loading by assetsManager...');
};
assetsManager.onFinish = function (task) {
//engine.hideLoadingUI();
engine.setSize($(window).width(), $(window).height());
engine.runRenderLoop(function () {
scene.render();
});
};
assetsManager.load();
// Resize
window.addEventListener("resize", function () {
engine.resize();
});
}else{
alert("Chyba: Nemôžem spustiť WebGL. (Error: Can't run WebGL.)");
}
</script>
</body></html>

reload canvas createjs/easeljs animation with ajax load causes layering or display issue

I have a canvas animation that has been created with createjs. The entire animation script including init() function is loaded via jquery: $.getScript() on page load.
The init() and handlecomplete() function included below is then run which attaches the animation to a html canvas element on the page.
var canvas, stage, exportRoot, audio;
var tweens = [];
function init() {
canvas = document.getElementById("canvas");
images = images||{};
if (stage) {
stage.enableDOMEvents(false);
stage.removeAllChildren();
createjs.Ticker.removeAllEventListeners()
stage.enableDOMEvents(true);
}
if (audio ) {
audio.stop();
}
removeTweens();
exportRoot = null;
audio = null;
stage = null;
var loader = new createjs.LoadQueue(false);
loader.installPlugin(createjs.Sound);
loader.addEventListener("fileload", handleFileLoad);
loader.addEventListener("complete", handleComplete);
loader.loadManifest(lib.properties.manifest);
}
function handleComplete() {
exportRoot = new lib.animation2();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
stage.canvas.width = 1280;
stage.canvas.height = 720;
resizeToFit();
stage.update();
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
createjs.Ticker.addEventListener("tick", updateTimer);
if (lib.properties.audiovolume) {
audio = createjs.Sound.play("audio", createjs.Sound.INTERRUPT_EARLY, 0, 0, -1, lib.properties.audiovolume);
}
exportRoot.gotoAndPlay(startFrame );
}
My issue is when the user makes a change, we load the script a second time using the same jquery method which returns the updated script. The init() function then executes properly and the new animation plays correctly, but our animated text (using the animateText below) does not appear on the canvas. This function is also loaded dynamically with other functions.
Checking the tween arrays, they are being created and removed as required, but they are not visible.
They are either layered behind the new animation, or not being attached to the new canvas or something else?
Simply refreshing the page will then load the new script and text properly. So clearly something in the dynamic loading of the script?
var animateText = function(localString, startX, startY, letterClip, endObject, font, color) {
var waitAmount = 0;
var offSetAmount = 20;
for(var i = 0; i < localString.length; i++){
var fl_MyInstance = new letterClip();
fl_MyInstance.localName.text = localString[i];
if(font != null){
fl_MyInstance.localName.font = font;
}
if(color != null){
fl_MyInstance.localName.color = color;
}
var localX = startX;
var localY = startY;
fl_MyInstance.x = startX + offSetAmount;
var beginX = startX + offSetAmount
offSetAmount = offSetAmount - 4
fl_MyInstance.y = startY;
fl_MyInstance.alpha = 0;
fl_MyInstance.scaleX = 0.1;
fl_MyInstance.scaleY = 0.1;
var bounds = fl_MyInstance.getBounds();
startX += bounds.width + 0;
var target = fl_MyInstance;
var tween = createjs.Tween.get(target, {
loop: false
}).wait(waitAmount)
.to({
x: localX,
y: localY,
alpha: 1,
scaleX: 1,
scaleY: 1
}, 400, createjs.Ease.circOut);
tween.waitAmount = waitAmount;
if(endObject == null){
tween.endObject = {
x: localX,
y: localY,
alpha: 0,
scaleX: 0.1,
scaleY: 0.1
}
} else {
tween.endObject = {
x: localX - endObject.x,
y: localY - endObject.y,
alpha: endObject.alpha,
scaleX: endObject.scaleX,
scaleY: endObject.scaleY
}
}
tween.targetClip = fl_MyInstance;
tween.arrayIndex = tweens.length;
tweens.push(tween);
waitAmount += 20;
stage.addChild(fl_MyInstance);
}
}
var removeTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
stage.removeChild(tween.targetClip);
tweens[tween.arrayIndex] = null;
}
}
}
var closeTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
createjs.Tween.get(tween.targetClip, {
loop: false
}).wait(tween.waitAmount).to(tween.endObject, 400, createjs.Ease.circOut).call(function(){
stage.removeChild(tween.targetClip);
tweens[tween.arrayIndex] = null;
});
}
}
}
var finalTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
createjs.Tween.get(tween.targetClip, {
loop: false
}).to(tween.endObject, 400, createjs.Ease.circOut);
}
}
}
Since the rest of the animation works perfectly using this method of dynamic loading, I don't think it is something in the loading. But there must be something missing in animateText and reloading functions that causes the issue.

Categories