How I can make a progressbar in PixiJS? - javascript

How I can make a progressbar like this in PixiJS?
Screenshot

I solved!
function BalanceBoard(data) {
this.gameObject = data['gameObject'];
this.text = data['text'];
this.posX = data['posX'];
this.posY = data['posY'];
this.spriteText;
this.spriteBorder = {
'frameindex': 0,
frames: [
'stats-border-1.png'
]
};
this.spriteBar = {
'frameindex': 0,
frames: [
'stats-bar-1.png'
]
};
}
BalanceBoard.prototype.build = function() {
this.spriteBorder['texture'] = PIXI.Texture.fromFrame(this.spriteBorder['frames'][0]);
this.spriteBorder['object'] = new PIXI.Sprite(this.spriteBorder['texture']);
this.spriteBorder['frameindex'] = 0;
this.spriteBorder['object'].anchor.x = 0.5;
this.spriteBorder['object'].anchor.y = 0.5;
this.spriteBorder['object'].position.x = -this.spriteBorder['object'].width;
this.spriteBorder['object'].position.y = -this.spriteBorder['object'].height;
gameObject.getStage().addChild(this.spriteBorder['object']);
this.spriteBar['texture'] = PIXI.Texture.fromFrame(this.spriteBar['frames'][0]);
this.spriteBar['object'] = new PIXI.Sprite(this.spriteBar['texture']);
this.spriteBar['frameindex'] = 0;
this.spriteBar['object'].anchor.x = 0.5;
this.spriteBar['object'].anchor.y = 0.5;
this.spriteBar['object'].position.x = -this.spriteBar['object'].width;
this.spriteBar['object'].position.y = -this.spriteBar['object'].height;
gameObject.getStage().addChild(this.spriteBar['object']);
this.spriteText = new PIXI.Text(this.text, {
font: '600 10pt Open Sans',
fill: 'white'
});
this.spriteText.position.x = this.getPosX() - this.spriteText.width / 2;
this.spriteText.position.y = this.getPosY() - this.spriteText.height / 2;
gameObject.getStage().addChild(this.spriteText);
};
BalanceBoard.prototype.update = function() {
this.spriteText.text = this.text;
this.spriteBorder['object'].position.x = this.getPosX();
this.spriteBorder['object'].position.y = this.getPosY();
this.spriteBar['object'].position.x = this.getPosX();
this.spriteBar['object'].position.y = this.getPosY();
this.spriteText.position.x = this.getPosX() - this.spriteText.width / 2;
this.spriteText.position.y = this.getPosY() - this.spriteText.height / 2;
};
BalanceBoard.prototype.getPosX = function() {
return this.spriteBorder['object'].width / 2 + this.posX;
};
BalanceBoard.prototype.getPosY = function() {
return this.spriteBorder['object'].height / 2 + this.posY;
};

Related

Drag object around a circle on mouse over - Adobe Animate/Create.js/Easel.js

Using Adobe Animate HTML5 Canvas which employs Create.js/Easel.js.
I have the following code which drags an object around a circle.
Works Ok, but the object should only be moveable when the cursor is over the object; object being streakRotatorKnob.
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
I have tried the following but it's not working at all with the if statement:
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
if(stage.mouseY == root.streakRotatorKnob.y && stage.mouseX == root.streakRotatorKnob.x){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
UPDATE
Based on Muhammed Maruf's answer below (the Adobe Animate version), the following works better by removing the line:
root.c.addEventListener("rollout", rollout);
So we just have:
stage.enableMouseOver();
var knob_X = 454;
var knob_Y = 169;
var radius = 90;
var root = this;
root.c.addEventListener("rollover", rollover);
//root.c.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.c.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.c.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
This is how I edited the code. I think you meant that.
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [];
(lib.AnMovieClip = function(){
this.actionFrames = [];
this.ignorePause = false;
this.gotoAndPlay = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndPlay.call(this,positionOrLabel);
}
this.play = function(){
cjs.MovieClip.prototype.play.call(this);
}
this.gotoAndStop = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndStop.call(this,positionOrLabel);
}
this.stop = function(){
cjs.MovieClip.prototype.stop.call(this);
}
}).prototype = p = new cjs.MovieClip();
// symbols:
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop, this.reversed));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
(lib.Sembol1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// Katman_1
this.shape = new cjs.Shape();
this.shape.graphics.f("#000000").s().p("AhuBuQgtguAAhAQAAg/AtguQAvguA/AAQBBAAAtAuQAuAuAAA/QAABAguAuQgtAuhBAAQg/AAgvgug");
this.timeline.addTween(cjs.Tween.get(this.shape).wait(1));
this._renderFirstFrame();
}).prototype = getMCSymbolPrototype(lib.Sembol1, new cjs.Rectangle(-15.6,-15.6,31.2,31.2), null);
// stage content:
(lib.index = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
this.actionFrames = [0];
this.isSingleFrame = false;
// timeline functions:
this.frame_0 = function() {
if(this.isSingleFrame) {
return;
}
if(this.totalFrames == 1) {
this.isSingleFrame = true;
}
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));
// Katman_1
this.streakRotatorKnob = new lib.Sembol1();
this.streakRotatorKnob.name = "streakRotatorKnob";
this.streakRotatorKnob.setTransform(207.8,131.8);
this.timeline.addTween(cjs.Tween.get(this.streakRotatorKnob).wait(1));
this._renderFirstFrame();
}).prototype = p = new lib.AnMovieClip();
p.nominalBounds = new cjs.Rectangle(467.2,316.2,-243.79999999999998,-168.79999999999998);
// library properties:
lib.properties = {
id: '214D9CE6C84FD84795816AF703BF00E4',
width: 550,
height: 400,
fps: 24,
color: "#CCCCCC",
opacity: 1.00,
manifest: [],
preloads: []
};
// bootstrap callback support:
(lib.Stage = function(canvas) {
createjs.Stage.call(this, canvas);
}).prototype = p = new createjs.Stage();
p.setAutoPlay = function(autoPlay) {
this.tickEnabled = autoPlay;
}
p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
an.bootcompsLoaded = an.bootcompsLoaded || [];
if(!an.bootstrapListeners) {
an.bootstrapListeners=[];
}
an.bootstrapCallback=function(fnCallback) {
an.bootstrapListeners.push(fnCallback);
if(an.bootcompsLoaded.length > 0) {
for(var i=0; i<an.bootcompsLoaded.length; ++i) {
fnCallback(an.bootcompsLoaded[i]);
}
}
};
an.compositions = an.compositions || {};
an.compositions['214D9CE6C84FD84795816AF703BF00E4'] = {
getStage: function() { return exportRoot.stage; },
getLibrary: function() { return lib; },
getSpriteSheet: function() { return ss; },
getImages: function() { return img; }
};
an.compositionLoaded = function(id) {
an.bootcompsLoaded.push(id);
for(var j=0; j<an.bootstrapListeners.length; j++) {
an.bootstrapListeners[j](id);
}
}
an.getComposition = function(id) {
return an.compositions[id];
}
an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {
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);
}
}
domContainers[0].width = w * pRatio * sRatio;
domContainers[0].height = h * pRatio * sRatio;
domContainers.forEach(function(container) {
container.style.width = w * sRatio + 'px';
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;
}
}
an.handleSoundStreamOnTick = function(event) {
if(!event.paused){
var stageChild = stage.getChildAt(0);
if(!stageChild.paused || stageChild.ignorePause){
stageChild.syncStreamSounds();
}
}
}
an.handleFilterCache = function(event) {
if(!event.paused){
var target = event.target;
if(target){
if(target.filterCacheList){
for(var index = 0; index < target.filterCacheList.length ; index++){
var cacheInst = target.filterCacheList[index];
if((cacheInst.startFrame <= target.currentFrame) && (target.currentFrame <= cacheInst.endFrame)){
cacheInst.instance.cache(cacheInst.x, cacheInst.y, cacheInst.w, cacheInst.h);
}
}
}
}
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
<!DOCTYPE html>
<!--
NOTES:
1. All tokens are represented by '$' sign in the template.
2. You can write your code only wherever mentioned.
3. All occurrences of existing tokens will be replaced by their appropriate values.
4. Blank lines will be removed automatically.
5. Remove unnecessary comments before creating your template.
-->
<html>
<head>
<meta charset="UTF-8">
<meta name="authoring-tool" content="Adobe_Animate_CC">
<title>index</title>
<!-- write your code here -->
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="index.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("214D9CE6C84FD84795816AF703BF00E4");
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.index();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.framerate = lib.properties.fps;
createjs.Ticker.addEventListener("tick", stage);
}
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(false,'both',false,1,[canvas,anim_container,dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<!-- write your code here -->
</head>
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(204, 204, 204, 1.00); width:550px; height:400px">
<canvas id="canvas" width="550" height="400" style="position: absolute; display: block; background-color:rgba(204, 204, 204, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:550px; height:400px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>
</html>
I just saw what you wrote because of the time difference.
Let me answer your last comment as follows. In the example I posted, I averaged over the canvas. While you are giving the starting position, you need to enter the initial position information as if you were rotating it. I also solved a problem with Mac devices. The example should be:
stage.enableMouseOver();
var knob_X = canvas.width/2/stage.scaleX;
var knob_Y = canvas.height/2/stage.scaleY;
var radius = 90;
var root = this;
var rads = Math.atan2(1-knob_Y,1-knob_X);
root.streakRotatorKnob.x = knob_X + radius * Math.cos(rads);
root.streakRotatorKnob.y = knob_Y + radius * Math.sin(rads);
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY/stage.scaleY - knob_Y, stage.mouseX/stage.scaleX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}

JavaScript returning multiple times when using return

I am trying to recieve data of multiple JSON files. I have the data I need, but multiple times, even though I use a return statement. I need the data from the getData() function. Which needs to progress to the loadImage() function. I have no clue why the code returns the same multiple times.
Thanks in advance.
My Chrome Developer Console:
My Directory Structure:
My code:
// var defaultHairData = require(['json!../character/hair/data.json'], function(data) {
// console.log("1", data);
// });
// var defaultHeadData = require("../character/head/data.json");
// var defaultLeftArmData = require("../character/leftArm/data.json");
// var defaultLegsData = require("../character/legs/data.json");
// var defaultRightArmData = require("../character/rightArm/data.json");
// var defaultTorsoData = require("../character/torso/data.json");
// var defaultHairImage = require("../character/hair/0/hair.png");
// var defaultHeadImage = require("../character/head/0/head.png");
// var defaultLeftArmImage = require("../character/leftArm/0/leftArm.png");
// var defaultLeftArmJumpImage = require("../character/leftArm_jump/0/leftArm_jump.png"); // Jump!
// var defaultLegsImage = require("../character/legs/0/legs.png");
// var defaultLegsJumpImage = require("../character/legs_jump/0/legs_jump.png"); // Jump!
// var defaultRightArmImage = require("../character/rightArm/0/rightArm.png");
// var defaultRightArmJumpImage = require("../character/rightArm_jump/0/rightArm_jump.png"); // Jump!
// var defaultTorsoImage = require("../character/torso/0/torso.png");
var character = {
name: "Homie",
jumping: false
}
var totalResources = 9;
var loadedResources = 0;
var fps = 30;
var characterXPos = 245;
var characterYPos = 185;
var characterEyesOpenTime = 0;
var characterMaxEyesHeight = 14;
var characterCursiveEyeHeight = characterMaxEyesHeight;
var characterTimeBetweenBlinks = 4000;
var characterBlinkUpdateTime = 200;
var characterBlinkTimer = setInterval(updateBlink, characterBlinkUpdateTime);
var FPSInterval = setInterval(updateFPS, 1000);
var characterCanvas;
var characterCanvasContext;
var breathAmount = 0;
var breathMax = 2;
var breathIncrease = 0.1;
var breathDirection = 1;
var breathInterval = setInterval(updateBreathing, 1000 / fps);
var cursiveFPS = 0;
var framesDrawn = 0;
window.defaultHairData = {};
function updateFPS() {
cursiveFPS = framesDrawn;
framesDrawn = 0;
}
// This is where I need the data from \/
function getData(characterPart) {
var xhr = new XMLHttpRequest();
xhr.open("GET", `./character/${characterPart}/data.json`);
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
console.log("Yoink", window.defaultData);
return window.defaultData = JSON.parse(xhr.response);
} else {
throw new Error(`Could not get file with the name "data.json" in the directory "${characterPart}".`);
}
}
xhr.send();
}
async function prepareCharacterCanvas(canvasContainer, canvasWidth, canvasHeight) {
characterCanvas = document.createElement('canvas');
characterCanvas.setAttribute('width', canvasWidth);
characterCanvas.setAttribute('height', canvasHeight);
characterCanvas.setAttribute('id', 'gameCanvas');
canvasContainer.appendChild(characterCanvas);
if (typeof G_vmlCanvasManager != 'undefined') {
characterCanvas = G_vmlCanvasManager.initElement(characterCanvas);
};
characterCanvasContext = characterCanvas.getContext('2d');
characterCanvas.width = characterCanvas.width;
characterCanvasContext.fillText("Loading...", 40, 140);
// This is where the data needs to come from
await getData("hair");
await getData("head");
await getData("leftArm");
await getData("legs");
await getData("rigthArm");
await getData("torso");
loadImage(`${defaultData.filename}`);
loadImage(`${defaultHeadData.filename}`);
loadImage(`${defaultLeftArmData.filename}`);
loadImage(`${defaultLegsData.filename}`);
loadImage(`${defaultRightArmData.filename}`);
loadImage(`${defaultTorsoData.filename}`);
}
function loadImage(datatags, picture) {
var generateButtons = Boolean;
if (datatags.filename !== picture.name) {
throw new Error("Datatag 'filename' must be the same as the picture name!");
} else {
if (datatags.fileExtension !== "png") {
throw new Error("Datatag 'fileExtension' must be png!");
} else {
if (datatags.customizeable === false) {
generateButtons = false;
} else {
generateButtons = true;
}
if (generateButtons === true) {
// Generate buttons here!
}
if (datatags.changesIfJumping === true) {
// Load normal image first here
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
}
pic.src = `../character/${datatags.filename}/0/${datatags.filename}.png`;
// Load image if jumping next
var jumpingPic = new Image();
jumpingPic.onload = function() {
resourceIsLoaded();
}
jumpingPic.src = `../character/${datatags.filename}_jump/0/${datatags.filename}_jump.png`;
}
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
}
pic.src = `../character/${datatags.filename}/0/${datatags.filename}.png`;
}
}
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
};
pic.src = `${pic}`;
};
function resourceIsLoaded() {
loadedResources += 1;
if (loadedResources === totalResources) {
setInterval(redrawCharacter(), 1000 / userFPS);
};
};
function redrawCharacter() {
var x = characterXPos;
var y = characterYPos;
var jumpHeight = 45;
characterCanvas.width = characterCanvas.width;
if (character.jumping === true) {
drawEyes(x + 40, y + 29, 100 - breathAmount, 4);
y -= jumpHeight;
characterCanvasContext.drawImage("leftArm_jump", x + 40, y - 42 - breathAmount);
characterCanvasContext.drawImage("legs_jump", x, y - 6);
characterCanvasContext.drawImage("rightArm_jump", x - 35, y - 42 - breathAmount);
} else {
drawEyes(x + 40, y + 29, 160 - breathAmount, 6);
characterCanvasContext.drawImage("leftArm", x + 40, y - 42 - breathAmount);
characterCanvasContext.drawImage("legs", x, y);
characterCanvasContext.drawImage("rightArm", x - 15, y - 42 - breathAmount);
};
characterCanvasContext.drawImage("torso", x, y - 50);
characterCanvasContext.drawImage("head", x - 10, y - 125 - breathAmount);
characterCanvasContext.drawImage("hair", x - 37, y - 138 - breathAmount);
characterCanvasContext.drawEyes(x + 47, y - 68 - breathAmount, 8, characterCursiveEyeHeight);
characterCanvasContext.drawEyes(x + 58, y - 68 - breathAmount, 8, characterCursiveEyeHeight);
};
function drawEyes(centerX, centerY, width, height) {
characterCanvasContext.beginPath();
characterCanvasContext.moveTo(centerX, centerY - height / 2);
characterCanvasContext.bezierCurveTo(
centerX + width / 2, centerY - height - 2,
centerX + width / 2, centerY + height / 2,
centerX, centerY + height / 2);
characterCanvasContext.bezierCurveTo(
centerX - width / 2, centerY + height / 2,
centerX - width / 2, centerY - height / 2,
centerX, centerY - height / 2);
characterCanvasContext.fillStyle = "black";
characterCanvasContext.fill();
characterCanvasContext.closePath();
};
function updateBreathing() {
if (breathDirection === 1) {
breathAmount -= breathIncrease;
if (breathAmount < -breathMax) {
breathDirection = -1;
};
} else {
breathAmount += breathIncrease;
if (breathAmount > breathMax) {
breathDirection = 1;
};
};
};
function updateBlink() {
characterEyesOpenTime += characterBlinkUpdateTime;
if (characterEyesOpenTime >= characterTimeBetweenBlinks) {
blink();
};
};
function blink() {
characterCursiveEyeHeight -= 1;
if (characterCursiveEyeHeight <= 0) {
characterEyesOpenTime = 0;
characterCursiveEyeHeight = characterMaxEyesHeight;
} else {
setTimeout(blink, 10);
};
};
function jump() {
if (character.jumping === false) {
character.jumping = true;
setTimeout(land, 500);
};
};
function land() {
character.jumping = false;
}
The JSON file structure:
{
"filename": "legs",
"fileExtension": "png",
"changesIfJumping": true,
"customizeable": true
}
Use more modern way - fetch instead xhr
async function getData(characterPart) {
try {
let response = await fetch(`./character/${characterPart}/data.json`);
return response.json()
} catch (e) {
throw new Error(`Could not get file with the name "data.json" in the directory "${characterPart}".`);
}
}
// TEST
async function start() {
window.defaultData = await getData('xxx');
}
start();

three.js how to make texture "generated" texture coordinate, like blender cycles

I'm trying to display a texture onto a cylinder object in THREE.js, and I want to texture to show up on the cylinder in a well... not so distorted way, here's how it looks now:
and that is just based off this simple texture:
I don't want it to be distorted / stretched along the edges of the cylinder, I would like it to look something like the "generated" texture coordinate in blender cycles:
(notice the "box" setting in the image texture)
SOOO I have no idea how to set the texture coordinates in THREE.js ... ?
EDIT::: There's been a request for the actual source code, so here it is (even though it's complicated):
var COBY = new (function() {
this.p = Processing;
this.t=THREE;
this.mouseX = 0;
this.mouseY = 0;
this.Keyboard = new (function() {
this.keysDown = [];
for(var i = 0; i < 200; i++) {
this.keysDown[i] = false;
}
this.RIGHT = 39;
this.LEFT = 37;
this.UP = 38;
this.DOWN = 40;
this.setKeyDown = function(key) {
COBY.Keyboard.keysDown[key] = true;
};
this.setKeyUp = function(key) {
COBY.Keyboard.keysDown[key] = false;
};
this.isKeyDown = function(key) {
return COBY.Keyboard.keysDown[key];
};
});
document.body.onkeydown = function(e) {
COBY.Keyboard.setKeyDown(e.keyCode);
};
document.body.onkeyup = function(e) {
COBY.Keyboard.setKeyUp(e.keyCode);
};
document.body.onmousemove = function(e) {
COBY.mouseX = e.x;
COBY.mouseY = e.y;
};
this.shapes = {
cube:new THREE.BoxGeometry(1,1,1),
cylinder: new THREE.CylinderGeometry(0.5, 0.5, 1),
plane: new THREE.PlaneBufferGeometry(1,1),
};
this.textures = {
white:new THREE.MeshLambertMaterial({color:"white"}),
red:new THREE.MeshLambertMaterial({color:"red"}),
purple:new THREE.MeshLambertMaterial({color:"purple"}),
blue:new THREE.MeshLambertMaterial({color:"blue"}),
pink:new THREE.MeshLambertMaterial({color:"pink"}),
gray:new THREE.MeshLambertMaterial({color:"gray"}),
yellow:new THREE.MeshLambertMaterial({color:"yellow"}),
green:new THREE.MeshLambertMaterial({color:"green"})
};
this.loadTexture = function(name, path) {
COBY.textures[name] = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture(path)
});
console.log(COBY.textures);
};
this.GUIContainer = function(obj) {
this.div = document.createElement("div");
this.div.style.position="absolute";
this.div.style.left=(obj.x || 0) + "px";
this.div.style.top=(obj.y || 0) + "px";
this.div.style.background=obj.color || "white";
this.div.style.width = (obj.width || 100) + "px";
this.div.style.height = (obj.height || 100) + "px";
this.div.style.display = obj.invisible ? "none" : "block";
var that = this;
this.add = function(g) {
that.div.appendChild(g.div);
};
if(document.body) {
document.body.appendChild(this.div);
}
};
this.GUIObject = function(obj) {
this.div = document.createElement("div");
this.div.style.position="absolute";
this.div.style.left=(obj.x || 0) + "px";
this.div.style.top=(obj.y || 0) + "px";
this.div.style.background=obj.color || "white";
this.div.style.width = (obj.width || 100) + "px";
this.div.style.height = (obj.height || 100) + "px";
if(obj.text) {
this.div.innerHTML = "<p class='gTxt'>" + obj.text + "</p>";
}
if(obj.type === "button") {
this.div.className = "btn";
}
};
this.Cobject = function(obj,world) {
this.width=obj.width||1;
this.height=obj.height||1;
this.depth=obj.depth||1;
this.position = new THREE.Vector3();
this.rotation = {x:0,y:0,z:0};
this.forReference = obj.forReference;
if(obj.position) {
this.position.x = obj.position.x || 0;
this.position.y = obj.position.y || 0;
this.position.z = obj.position.z || 0;
}
if(obj.rotation) {
this.rotation.x = obj.rotation.x || 0;
this.rotation.y = obj.rotation.y || 0;
this.rotation.z = obj.rotation.z || 0;
}
this.worldParent = world || false;
this.followMouse = obj.followMouse || false;
this.update=obj.update||function(c){};
this.start = obj.start || function(){};
this.texture = COBY.textures[obj.texture];
//this.texture.wrapS = this.texture.wrapT = THREE.MirroredRepeatWrapping;
this.mesh=new THREE.Mesh(COBY.shapes[obj.shape],this.texture);
var self = this;
this.updateTexture = function(path) {
self.mesh.material.map.image.src = path;
self.mesh.material.needsUpdate = true;
}
this.superUpdate = function(cob) {
self.mesh.scale.set(self.width,self.height,self.depth);
self.mesh.position.copy(self.position);
self.mesh.rotation.set(self.rotation.x,self.rotation.y,self.rotation.z);
self.update(cob);
};
};
function webglAvailable() {
try {
var canvas = document.createElement( 'canvas' );
return !!( window.WebGLRenderingContext && (
canvas.getContext( 'webgl' ) ||
canvas.getContext( 'experimental-webgl' ) )
);
} catch ( e ) {
return false;
}
}
this.World=function (obj) {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.loadTextures = function(texts) {
for(var i = 0; i < texts.length; i++) {
COBY.loadTexture(texts[i].name, texts[i].path);
}
};
if(obj) {
this.width=obj.width || window.innerWidth;
this.height=obj.height || window.innerHeight;
if(obj.textures) {
this.loadTextures(obj.textures);
}
}
this.scene=new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 75, this.width / this.height, 0.1, 10000 );
this.camera.name = "camera";
//if ( webglAvailable() ) {
this.renderer = new THREE.WebGLRenderer({alpha:true});
// } else {
// this.renderer = new THREE.CanvasRenderer();
// }
this.renderer.setSize(this.width,this.height);
this.renderer.setClearColor(0x000000, 0);
this.renderer.domElement.style.position="absolute";
this.renderer.domElement.style.left="0";
this.renderer.domElement.style.top="0";
this.camera.position.z=5;
this.cobs = [];
this.meshes=[];
var that=this;
this.light = function(x,y,z,inten) {
var directionalLight1=new THREE.DirectionalLight(0xffffff);
directionalLight1.position.set(x,y,z,inten || 1);
directionalLight1.name == "light";
that.scene.add(directionalLight1);
};
this.lights = function() {
var ambientLight = new THREE.AmbientLight( 0x606060 );
that.scene.add( ambientLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 1, 0.75, -0.5 ).normalize();
that.scene.add( directionalLight );
};
this.lights();
this.add=function(obj){
if(!obj.forReference) {
if(obj.mesh) {
that.scene.add(obj.mesh);
that.meshes.push(obj.mesh);
that.cobs.push(obj);
} else {
that.scene.add(obj);
}
}
obj.start(obj);
};
this.cob = function(c) {
that.add(new COBY.Cobject(c,that));
};
this.addCobjects = function(cobs) {
for(var i = 0; i < cobs.length; i++) {
that.add(new COBY.Cobject(cobs[i],that));
}
};
this.empty = function() {
that.meshes = [];
that.cobs = [];
for(var i = that.scene.children.length - 1; i >= 0; i--) {
that.scene.remove(that.scene.children[i]);
}
that.scene.add(that.camera);
that.lights();
console.log("just actually emptied..feels good");
};
this.update=function (){
// noprotect
for(var i=0;i<that.cobs.length;i++) {
that.cobs[i].superUpdate(that.cobs[i]);
}
that.loop();
that.renderer.render(that.scene, that.camera);
};
this.loop=function(){
};
this.canvas=this.renderer.domElement;
this.start = function(div) {
if(!div)
document.body.appendChild(this.canvas);
else
div.appendChild(this.canvas);
function sketchProc(proc) {
// noprotect
proc.draw=function(){
that.update();
};
}
var procInst=new Processing(document.createElement("canvas"),sketchProc);
};
};
})();
Both THREE.CylinderGeometry() and THREE.CylinderBufferGeometry() work as expected:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.setScalar(10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x404040);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
//var cylGeom = new THREE.CylinderGeometry(5, 5, 1, 8);
var cylGeom = new THREE.CylinderBufferGeometry(5, 5, 1, 8);
var texLoader = new THREE.TextureLoader();
var texEnd = texLoader.load("https://threejs.org/examples/textures/UV_Grid_Sm.jpg");
texEnd.wrapS = THREE.RepeatWrapping;
texEnd.wrapT = THREE.RepeatWrapping;
texEnd.repeat.set(1, 1);
var texSide = texLoader.load("https://threejs.org/examples/textures/UV_Grid_Sm.jpg");
texSide.wrapS = THREE.RepeatWrapping;
texSide.wrapT = THREE.RepeatWrapping;
texSide.repeat.set(1, 1 / (cylGeom.parameters.radiusTop * cylGeom.parameters.radiusBottom));
var cylMatEnd = new THREE.MeshBasicMaterial({
map: texEnd
});
var cylMatSide = new THREE.MeshBasicMaterial({
map: texSide
});
var cyl = new THREE.Mesh(cylGeom, [cylMatSide, cylMatEnd, cylMatEnd]);
scene.add(cyl);
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

TweenJS animation not working

I am working on a tool to perform sequence of animations by updating an object array. This array would have all the parameters to customize animation as per varied requirements. This tool is being developed with JavaScript and makes use of createJS library and TweenJS to animate objects. Objects are created dynamically and positioned, then the tween is applied. Tween doesn't seem to work in my code.
I have the whole code below
var AnimationFlow = (function () {
'use strict';
var AnimationFlow = function (canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function (data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({'src': this.animData[i].targeturl, 'id': this.animData[i].targetID});
}
};
AnimationFlow.prototype.init = function () {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function () {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function () {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function () {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function () {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if(this.animData[i].isAnimatable){
var c = createjs.Tween.get(this.obj);
c.to({x:this.animData[i].params.xpos}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.stage.update();
};
AnimationFlow.prototype.tick = function () {
console.log("heart beat on....");
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function () {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function () {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{targetID: 'background', targeturl: 'assets/images/heliGame/sky.png',isAnimatable:true, duration: 2000, params: {xpos: '600'}, isVisibleAfterAnimation: true, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'},
{targetID: 'mousePointer', targeturl: 'assets/images/heliGame/helicopter.png',isAnimatable:true, duration: 1000, params: {xpos: '500'}, isVisibleAfterAnimation: false, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
I have the code in JSFiddle
https://jsfiddle.net/jamesshaji/t4pxzsoo/
There were a couple of issues. Firstly, you need to define all of your positions as integers and not as strings (ie: take the quotes off of your position data in your data object). Secondly, you need to call: this.timeline.gotoAndPlay(0); to start the timeline execution. Otherwise the animations won't play. Here is a fixed version:
var AnimationFlow = (function() {
'use strict';
var AnimationFlow = function(canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function(data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({
'src': this.animData[i].targeturl,
'id': this.animData[i].targetID
});
}
};
AnimationFlow.prototype.init = function() {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function() {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function() {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function() {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function() {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if (this.animData[i].isAnimatable) {
console.log("animatable:" + this.animData[i].params.xpos + " " + this.animData[i].duration);
var c = createjs.Tween.get(this.obj);
c.to({
x: this.animData[i].params.xpos
}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.timeline.gotoAndPlay(0);
this.stage.update();
};
AnimationFlow.prototype.tick = function() {
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function() {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function() {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{
targetID: 'background',
targeturl: 'https://s13.postimg.org/tyj4iop93/Sky_Pic.jpg',
isAnimatable: true,
duration: 2000,
params: {
xpos: -100
},
isVisibleAfterAnimation: true,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 0,
initialYPos: 0
}, {
targetID: 'mousePointer',
targeturl: 'http://jamesshaji.com/angular/assets/images/heliGame/helicopter.png',
isAnimatable: true,
duration: 2000,
params: {
xpos: 100
},
isVisibleAfterAnimation: false,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 450,
initialYPos: 50
}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tweenjs/0.6.2/tweenjs.min.js"></script>
<div>Animation</div>
<canvas height="500" width="500" id="testCanvas">
</canvas>

javascript function didn't work in chrome

i have this function witch shows the user a loadingpanel at postback.
It works fine in IE and Firefox.
But Chrome showed me this Error:
I don't understand why. Does anyone have an idea?
I mean why it works in IE and Firefox. Where is the difference that it doesn't work in Chrome?
(function(){
var emptyFn = function(){};
function lp(d) {
this.converter = d.converter;
this.data = d.path || d.data;
this.imageData = [];
this.multiplier = d.multiplier || 1;
this.padding = d.padding || 0;
this.fps = d.fps || 25;
this.stepsPerFrame = ~~d.stepsPerFrame || 1;
this.trailLength = d.trailLength || 1;
this.pointDistance = d.pointDistance || .05;
this.domClass = d.domClass || 'lp';
this.backgroundColor = d.backgroundColor || 'rgba(0,0,0,0)';
this.fillColor = d.fillColor;
this.strokeColor = d.strokeColor;
this.stepMethod = typeof d.step == 'string' ?
stepMethods[d.step] :
d.step || stepMethods.square;
this._setup = d.setup || emptyFn;
this._teardown = d.teardown || emptyFn;
this._preStep = d.preStep || emptyFn;
this.width = d.width;
this.height = d.height;
this.fullWidth = this.width + 2*this.padding;
this.fullHeight = this.height + 2*this.padding;
this.domClass = d.domClass || 'lp';
this.setup();
}
var argTypes = lp.argTypes = {
DIM: 1,
DEGREE: 2,
RADIUS: 3,
OTHER: 0
};
var argSignatures = lp.argSignatures = {
arc: [1, 1, 3, 2, 2, 0],
bezier: [1, 1, 1, 1, 1, 1, 1, 1],
line: [1,1,1,1]
};
var pathMethods = lp.pathMethods = {
bezier: function(t, p0x, p0y, p1x, p1y, c0x, c0y, c1x, c1y) {
t = 1-t;
var i = 1-t,
x = t*t,
y = i*i,
a = x*t,
b = 3 * x * i,
c = 3 * t * y,
d = y * i;
return [
a * p0x + b * c0x + c * c1x + d * p1x,
a * p0y + b * c0y + c * c1y + d * p1y
]
},
arc: function(t, cx, cy, radius, start, end) {
var point = (end - start) * t + start;
var ret = [
(Math.cos(point) * radius) + cx,
(Math.sin(point) * radius) + cy
];
ret.angle = point;
ret.t = t;
return ret;
},
line: function(t, sx, sy, ex, ey) {
return [
(ex - sx) * t + sx,
(ey - sy) * t + sy
]
}
};
var stepMethods = lp.stepMethods = {
square: function(point, i, f, color, alpha) {
this._.fillRect(point.x - 3, point.y - 3, 6, 6);
},
fader: function(point, i, f, color, alpha) {
this._.beginPath();
if (this._last) {
this._.moveTo(this._last.x, this._last.y);
}
this._.lineTo(point.x, point.y);
this._.closePath();
this._.stroke();
this._last = point;
}
}
lp.prototype = {
setup: function() {
var args,
type,
method,
value,
data = this.data;
this.canvas = document.createElement('canvas');
this._ = this.canvas.getContext('2d');
this.canvas.className = this.domClass;
this.canvas.height = this.fullHeight;
this.canvas.width = this.fullWidth;
this.canvas.innerHTML = "<img src='../img/ContentLoad.gif' width='60px' height='60px' alt='Wird geladen' style='margin-top: 30px;' />"
this.points = [];
for (var i = -1, l = data.length; ++i < l;) {
args = data[i].slice(1);
method = data[i][0];
if (method in argSignatures) for (var a = -1, al = args.length; ++a < al;) {
type = argSignatures[method][a];
value = args[a];
switch (type) {
case argTypes.RADIUS:
value *= this.multiplier;
break;
case argTypes.DIM:
value *= this.multiplier;
value += this.padding;
break;
case argTypes.DEGREE:
value *= Math.PI/180;
break;
};
args[a] = value;
}
args.unshift(0);
for (var r, pd = this.pointDistance, t = pd; t <= 1; t += pd) {
t = Math.round(t*1/pd) / (1/pd);
args[0] = t;
r = pathMethods[method].apply(null, args);
this.points.push({
x: r[0],
y: r[1],
progress: t
});
}
}
this.frame = 0;
if (this.converter && this.converter.setup) {
this.converter.setup(this);
}
},
prep: function(frame) {
if (frame in this.imageData) {
return;
}
this._.clearRect(0, 0, this.fullWidth, this.fullHeight);
this._.fillStyle = this.backgroundColor;
this._.fillRect(0, 0, this.fullWidth, this.fullHeight);
var points = this.points,
pointsLength = points.length,
pd = this.pointDistance,
point,
index,
frameD;
this._setup();
for (var i = -1, l = pointsLength*this.trailLength; ++i < l && !this.stopped;) {
index = frame + i;
point = points[index] || points[index - pointsLength];
if (!point) continue;
this.alpha = Math.round(1000*(i/(l-1)))/1000;
this._.globalAlpha = this.alpha;
if (this.fillColor) {
this._.fillStyle = this.fillColor;
}
if (this.strokeColor) {
this._.strokeStyle = this.strokeColor;
}
frameD = frame/(this.points.length-1);
indexD = i/(l-1);
this._preStep(point, indexD, frameD);
this.stepMethod(point, indexD, frameD);
}
this._teardown();
this.imageData[frame] = (
this._.getImageData(0, 0, this.fullWidth, this.fullWidth)
);
return true;
},
draw: function() {
if (!this.prep(this.frame)) {
this._.clearRect(0, 0, this.fullWidth, this.fullWidth);
this._.putImageData(
this.imageData[this.frame],
0, 0
);
}
if (this.converter && this.converter.step) {
this.converter.step(this);
}
if (!this.iterateFrame()) {
if (this.converter && this.converter.teardown) {
this.converter.teardown(this);
this.converter = null;
}
}
},
iterateFrame: function() {
this.frame += this.stepsPerFrame;
if (this.frame >= this.points.length) {
this.frame = 0;
return false;
}
return true;
},
play: function() {
this.stopped = false;
var hoc = this;
this.timer = setInterval(function(){
hoc.draw();
}, 1000 / this.fps);
},
stop: function() {
this.stopped = true;
this.timer && clearInterval(this.timer);
}
};
window.lp = lp;
}());
function ContentLoader(e) {
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
if (isIE () == 8) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = '../img/ContentLoad.gif';
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; filter: alpha(opacity=70);';
div.appendChild(img);
img.style.cssText = 'margin-top:20px;'
document.body.appendChild(div);
} else {
var div = document.createElement('div');
var circle = new lp({
width: 60,
height: 60,
padding: 50,
strokeColor: '#1d4377',
pointDistance: .01,
stepsPerFrame: 4,
trailLength: .8,
step: 'fader',
setup: function () {
this._.lineWidth = 5;
},
path: [
['arc', 25, 25, 25, 0, 360]
]
});
circle.play();
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; opacity: 0.7;';
div.appendChild(circle.canvas);
document.body.appendChild(div);
}
}
Edit:
I call it like this:
<form id="frmTilgungsaussetzungErgebnis" runat="server" enctype="multipart/form-data" onsubmit="ContentLoader();">
Your function lp is not defined in the else scope.
Try
var circle = new this.lp({
instade
var circle = new lp({

Categories

Resources