Related
Hello everyone I have such a problem. I have two scripts, anim.js and main.js . In anim.js describes the animation, and in main.js I'm trying to make a stop by pressing a button. I'm trying to make a stop through timeline, but I can't access timeline in main.js, timeline initialize in the file anim.js
anim.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="Adobe_Animate_CC" name="authoring-tool">
<title>anim</title>
<!-- write your code here -->
<style>
#animation_container {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
body, canvas {
background: none transparent !important;
}
</style>
<script src="../js/libs/adobe/createjs.js"></script>
<script src="anim.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("4D38855BFA773041952A1579DB0CC3CC");
var lib = comp.getLibrary();
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", function (evt) {
handleFileLoad(evt, comp)
});
loader.addEventListener("complete", function (evt) {
handleComplete(evt, comp)
});
var lib = comp.getLibrary();
loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt, comp) {
var images = comp.getImages();
if (evt && (evt.item.type == "image")) {
images[evt.item.id] = evt.result;
}
}
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();
var queue = evt.target;
var ssMetadata = lib.ssMetadata;
for (i = 0; i < ssMetadata.length; i++) {
ss[ssMetadata[i].name] = new createjs.SpriteSheet({
"images": [queue.getResult(ssMetadata[i].name)],
"frames": ssMetadata[i].frames
})
}
exportRoot = new lib.anim();
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);
};
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(true, 'both', true, 1, [canvas, anim_container, dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<script src="../js/main.js"></script>
<script>
function doLoadIframe() {
console.log('catch1');
let msg = function() {
p = 'привет';
return p;
}
//отправка события родителю
parent.postMessage(msg(), '*');
parent.focus();
init();
//setTimeout(stpAnimDef, 100);
}
</script>
<script>
window.addEventListener("message", function(msg){
console.log(msg.data);
if (msg.data == 'stop') {
stopAnimation();
} else if (msg.data == 'play'){
playAnimation();
}
let text = document.querySelector('.textAnim');
text.value = msg.data;
});
</script>
<!-- write your code here -->
</head>
<body onload="doLoadIframe();" style="margin:0px;">
<div id="animation_container" style="width:1280px; height:720px">
<canvas height="720" id="canvas"
style="position: absolute; display: block;"
width="1280"></canvas>
<div id="dom_overlay_container"
style="pointer-events:none; overflow:hidden; width:1280px; height:720px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
<input type='text' class='textAnim' />
</body>
</html>
anim.js
var timeline = new createjs.Timeline({paused: true});
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [
{name:"anim_atlas_", frames: [[0,0,233,233]]}
];
// symbols:
(lib.CachedTexturedBitmap_1 = function() {
this.initialize(ss["anim_atlas_"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop));
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.Символ1 = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Слой_1
this.instance = new lib.CachedTexturedBitmap_1();
this.instance.parent = this;
this.instance.setTransform(-0.5,-0.5,0.5,0.5);
var t = cjs.Tween.get(this.instance).wait(1);
timeline.addTween(t/*cjs.Tween.get(this.instance).wait(1)*/);
}).prototype = getMCSymbolPrototype(lib.Символ1, new cjs.Rectangle(-0.5,-0.5,116.5,116.5), null);
// stage content:
(lib.anim = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Слой_1
this.instance = new lib.Символ1();
this.instance.parent = this;
this.instance.setTransform(210.85,268.85,1,1,0,0,0,57.8,57.8);
var t1 = cjs.Tween.get(this.instance).wait(1).to({x:243.8},0).wait(1).to({x:276.8},0).wait(1).to({x:309.8},0).wait(1).to({x:342.8},0).wait(1).to({x:375.8},0).wait(1).to({x:408.8},0).wait(1).to({x:441.8},0).wait(1).to({x:474.8},0).wait(1).to({x:507.8},0).wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1)
.call(function(){
this.dispatchEvent("foo");
}, null, timeline);
timeline.addTween(t1);
timeline.setPaused(false);
//this.timeline.addTween(cjs.Tween.get(this.instance, {reversed:true})./*wait(1).to({x:243.8},0).wait(1).to({x:276.8},0).wait(1).to({x:309.8},0).wait(1).to({x:342.8},0).wait(1).to({x:375.8},0).wait(1).to({x:408.8},0).wait(1).to({x:441.8},0).wait(1).to({x:474.8},0).wait(1).to({x:507.8},0).*/wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1));
//this.timeline.addTween(cjs.Tween.get(this.instance).wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:969.75},0).wait(1).to({x:936.75},0).wait(1).to({x:903.75},0).wait(1).to({x:870.75},0).wait(1).to({x:837.75},0).wait(1).to({x:804.75},0).wait(1).to({x:771.75},0).wait(1).to({x:738.75},0).wait(1).to({x:705.75},0).wait(1).to({x:672.8},0).wait(1).to({x:639.8},0).wait(1).to({x:606.8},0).wait(1).to({x:573.8},0).wait(1).to({x:540.8},0).wait(1));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(792.6,570.6,433.30000000000007,-243.5);
// library properties:
lib.properties = {
id: '4D38855BFA773041952A1579DB0CC3CC',
width: 1280,
height: 720,
fps: 20,
color: "#FFFFFF",
opacity: 1.00,
manifest: [
{src:"images/anim_atlas_.png", id:"anim_atlas_"}
],
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['4D38855BFA773041952A1579DB0CC3CC'] = {
getStage: function() { return exportRoot.getStage(); },
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;
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
main.js
function stopAnimation() {
console.log(timeline);
}
Cut and paste you all script to bottom of body htm tag
I have a collection of data representing cloud height measurements every minute. As new data arrives, i want to add them on the right side of the canvas, moving the older data to the left. Is it possible to do this without using a specific charting library like canvasjs?
Some additional info to make things a little bit clearer. If the webpage is opened, data of the last 180 minutes are queried by an Ajax call. The data is in json format.
<style>
canvas {
background-color: #ffffff;
}
</style>
<fieldset>
<legend>Wolkenhöhen:</legend>
<div id="theCanvas">
<canvas id="cloudCanvas" width="618" height="510" style="border:1px solid #ffffff;">
</canvas>
</div>
<script>
const blu = '#1c29cc';
const wht = '#000000';
const grn = '#008513';
const ylo = '#e2ff28';
const amb = '#9d4600';
const red = '#9d0313';
const gray = '#8f8481';
const black = '#000000';
var maxY = 510;
var minY = 15;
var minX = 10;
var maxX = 600;
function plotGrit() {
var c = document.getElementById("cloudCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(minX+20, minY);
ctx.lineTo(minX+20, maxY-15);
ctx.lineTo(maxX-15, maxY-15);
ctx.strokeStyle = '#c9c9c9';
ctx.stroke();
ctx.closePath();
ctx.font = "10px Arial";
};
function heightLine(hcld,ctxt) {
var arr = {"#9d4600":200,"#e2ff28":300,"#008513":700,"#000000":1500,"#1c29cc":2500};
for (i=0; i<hcld; i+=2000) {
ctxt.beginPath();
ctxt.moveTo(minX+20, (480-480*i/hcld)+minY);
ctxt.lineTo(maxX-15, (480-480*i/hcld)+minY);
ctxt.strokeStyle = gray;
ctxt.stroke();
ctxt.closePath();
ctxt.fillStyle = black;
ctxt.fillText(i, minX-10, (480-480*i/hcld)+minY);
}
for(var key in arr)
{
var hgt = arr[key];
ctxt.beginPath();
ctxt.moveTo(minX+20, (480-480*hgt/hcld)+minY);
ctxt.lineTo(maxX-15, (480-480*hgt/hcld)+minY);
ctxt.strokeStyle = key;
ctxt.stroke();
ctxt.closePath();
}
}
function timeLine(x,ctxt, col) {
ctxt.beginPath();
ctxt.moveTo(x, minY);
ctxt.lineTo(x, maxY-15);
ctxt.lineWidth = 1;
ctxt.strokeStyle = col;
ctxt.stroke();
ctxt.closePath();
}
function cldDot(hgt, x, y ,ctxt) {
// plots a dot representing the measured cloud height
if (hgt >= 2500) {
col = blu;
} else if (hgt >= 1500) {
col = wht;
} else if (hgt >= 700) {
col = grn;
} else if (hgt >= 300) {
col = ylo;
} else if (hgt >= 200) {
col = amb;
} else if ((hgt > 0) && (hgt < 200)) {
col = red;
}
ctxt.fillStyle = col;
ctxt.fillRect(x-3,y-3,3,3);
}
function fetchClouds() {
var multiplier = 1/1000;
var lcld = 400000;
var hcld = 0;
var X = minX+20;
var c = document.getElementById("cloudCanvas");
var ctx = c.getContext("2d");
$.ajax({
type: "Post",
url: "cloudQuery.php?tsteps=180",
success: function(data) {
var obj = $.parseJSON(data);
// Printing all the values from the resulting object
for (var i in obj ) {
cld = obj[i]['cldLyr_Service1'];
cld2 = obj[i]['cldLyr_Service2'];
cld3 = obj[i]['cldLyr_Service3'];
if (cld < lcld && cld != 0) {
lcld = cld;
}
if (cld > hcld) {
hcld = cld;
}
var min = obj[i]['Time'].substring(3,5);
if (min == 00) {
timeLine(X,ctx,black);
ctx.fillStyle = "black";
ctx.fillText(obj[i]['Time'], X-13, maxY-5);
}
if ((min % 10 == 0) && (min != 00)) {
timeLine(X,ctx,gray);
ctx.fillStyle = "black";
ctx.fillText(min, X-7, maxY-5);
}
cldDot(cld, X,(480-480*cld/hcld)+minY,ctx);
if (cld2 > 0) {
cldDot(cld2, X,(480-480*cld2/hcld)+minY,ctx);
}
if (cld3 > 0) {
cldDot(cld3, X,(480-480*cld3/hcld)+minY,ctx);
}
X+=3;
}
heightLine(hcld,ctx);
lcld = 0 + " ft";
ctx.fillStyle = "black";
ctx.fillText(lcld, minX-10, maxY-15);
hcld = hcld + " ft";
ctx.fillText(hcld, minX-10, maxY-490);
}
});
};
fetchClouds();
plotGrit();
$(document).ready(function() {
setInterval(fetchClouds, 1000);
});
</script>
</fieldset>
The result looks like
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>
I am developing a view for some items in my web site. Currently I have the items displayed in the HTML but now I need to draw some lines between the elements that will represent a connection between them, it's like a Gantt Chart but it doesn't include any time functionality, I only need to connect the items with the ones associated to them. I'm using JSTL to bring some data from a controller and I managed to draw the elements like the following image: http://i271.photobucket.com/albums/jj131/djrickel/before.png
And the way I need to display is in the following image:
http://i271.photobucket.com/albums/jj131/djrickel/after.png
This is how I'm creating my table containing the elements that I want to display:
<div class="container">
<table>
<tbody>
<c:forEach items="${nodeGraphs}" var="nodeGraph">
<tr>
<c:forEach var="i" begin="0" end="5">
<td>
<c:if test="${nodeGraph.columnID == i}">
<label class="label label-default">${nodeGraph.nodeObject.item.type}${nodeGraph.nodeObject.item.contextId}</label>
</c:if>
</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</div>
Does anyone know a way to create connecting lines between the elements using JQuery, JSon, Javascript or any HTML process? I can change from the table I'm using to div or span without any issue. I'm just looking the best way to display the information. Thanks in advance.
Probably the best way to do that is use HTML5 canvas, but if You want use div's try use this code:
(On JSFiddle: http://fiddle.jshell.net/22rar61n/9/)
var Line = (function() {
var diff = function(a, b) {
var d = Math.abs(a - b);
if (d === 0) {
d = 1;
}
return d;
}
var countWidth = function(line) {
return diff(line.endX, line.startX);
};
var countHeight = function(line) {
return diff(line.endY, line.startY);
};
var Line = function(options) {
this.startX = options.startX;
this.startY = options.startY;
this.endX = options.endX;
this.endY = options.endY;
}
Line.prototype.drowIn = function($container) {
var self = this;
var line = jQuery("<div></div>", {
class: "line " + self.LineType(),
css: {
"color": "red",
"top": self.startY,
"left": self.startX,
"width": countWidth(self),
"height": countHeight(self),
"background-color": "#000"
}
});
$container.append(line);
};
Line.prototype.LineType = function() {
if (this.startX != this.endX) {
return "horizontal";
}
return "vertical";
}
return Line;
})();
var Arrow = (function() {
var Arrow = function(start, end) {
this.start = start;
this.end = end;
}
Arrow.prototype.drowIn = function($container) {
var ArrowContainer = jQuery("<div></div>", {
class: "arrowContainer"
});
var line1 = new Line({
startX: this.start.x,
startY: this.start.y,
endX: this.start.x,
endY: this.end.y
});
line1.drowIn(ArrowContainer);
var line2 = new Line({
startX: this.start.x,
startY: this.end.y,
endX: this.end.x,
endY: this.end.y
});
line2.drowIn(ArrowContainer);
$container.append(ArrowContainer);
}
return Arrow;
})();
var Element = (function() {
var Element = function(options) {
var op = jQuery.extend({}, options);
this.x = op.x || -1;
this.y = op.y || -1;
this.content = op.content || "";
this.container = op.$container || "";
this.node = null;
this.subElements = [];
};
Element.prototype.addSubElement = function(element) {
element.container = this.container;
element.content = this.content + "." + (this.subElements.length + 1);
this.subElements.push(element);
};
Element.prototype.drow = function() {
var self = this;
this.node = jQuery("<div></div>", {
class: "element",
text: this.content,
css: {
top: self.y,
left: self.x
}
});
this.container.append(this.node);
var nexLvl = 0;
var lastHeight = nexLvl;
var lastLvl = 0;
var oldIndex = -1;
var outerHeightAndTop = jQuery(self.node).outerHeight() + jQuery(self.node).offset().top;
jQuery.each(this.subElements, function(index, element) {
var height = outerHeightAndTop * (index + 1 + lastLvl);
if (lastHeight != 0) {
height = lastHeight + outerHeightAndTop;
}
if (nexLvl != 0) {
oldIndex = index;
height = height + ((jQuery(self.node).outerHeight()) * nexLvl);
lastLvl = nexLvl;
}
lastHeight = height;
nexLvl = element.getMaxLevel();
element.x = jQuery(self.node).outerWidth() + jQuery(self.node).offset().left;
element.y = height;
element.drow();
self.connectWith(element);
});
};
Element.prototype.connectWith = function(element) {
var startY = jQuery(this.node).outerHeight() + this.y;
var startX = (jQuery(this.node).outerWidth() / 2) + this.x;
var endY = (jQuery(element.node).outerHeight() / 2) + element.y;
var arrow = new Arrow({
x: startX,
y: startY
}, {
x: element.x,
y: endY
});
arrow.drowIn(this.container);
};
function getLevelOnPosition(index) {
return this.subElements[index].getMaxLevel();
}
Element.prototype.getMaxLevel = function(initLvl) {
var lvl = initLvl || 0;
var maxLvl = lvl;
if (this.subElements.length > 0) {
maxLvl = lvl++;
}
jQuery.each(this.subElements, function(index, element) {
lvl = element.getMaxLevel(lvl);
if (lvl > maxLvl) {
maxLvl = lvl;
}
});
return maxLvl;
}
return Element;
})();
jQuery(document).ready(function() {
var container = jQuery("#container");
var e = new Element({
x: 10,
y: 10,
content: "a1",
$container: container
});
var sube = new Element();
e.addSubElement(sube);
var sube2 = new Element();
sube.addSubElement(sube2);
sube2.addSubElement(new Element());
var e2 = new Element();
e.addSubElement(e2);
e2.addSubElement(new Element());
e.addSubElement(new Element());
e.drow();
});
#container {
position: relative;
}
#container > .element {
position: absolute;
border: 1px solid black;
background-color: gray;
color: white;
padding: 2px;
z-index: 10;
}
#container > .arrowContainer {
position: absolute;
}
#container > .arrowContainer > .line {
position: absolute;
z-index: 50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>
I found this game online and am trying to get it to run from my desktop. Is there something special that a person has to do with the URL's or images to make the file recognize were everything is running and located at. I have all of the files and .png files in one folder and on the same level.
I would think that I should see the game on the screen. It is like a left to right horizontal scroll-er with enemy ships that come out of the right side of the screen and the main ship is on the right side of the screen. (Similar to that of the old style defender game)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div id="game-over-overlay"></div>
<div id="game-over">
<h1>GAME OVER</h1>
<button id="play-again">Play Again</button>
</div>
<div class="wrapper">
<div id="instructions">
<div>
move with <span class="key">arrows</span> or <span class="key">wasd</span>
</div>
<div>
shoot with <span class="key">space</span>
</div>
</div>
<div id="score"></div>
</div>
<script type="text/javascript" src="resources.js"></script>
<script type="text/javascript" src="input.js"></script>
<script type="text/javascript" src="sprite.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
sprite.js
(function() {
function Sprite(url, pos, size, speed, frames, dir, once) {
this.pos = pos;
this.size = size;
this.speed = typeof speed === 'number' ? speed : 0;
this.frames = frames;
this._index = 0;
this.url = url;
this.dir = dir || 'horizontal';
this.once = once;
};
Sprite.prototype = {
update: function(dt) {
this._index += this.speed*dt;
},
render: function(ctx) {
var frame;
if(this.speed > 0) {
var max = this.frames.length;
var idx = Math.floor(this._index);
frame = this.frames[idx % max];
if(this.once && idx >= max) {
this.done = true;
return;
}
}
else {
frame = 0;
}
var x = this.pos[0];
var y = this.pos[1];
if(this.dir == 'vertical') {
y += frame * this.size[1];
}
else {
x += frame * this.size[0];
}
ctx.drawImage(resources.get(this.url),
x, y,
this.size[0], this.size[1],
0, 0,
this.size[0], this.size[1]);
}
};
window.Sprite = Sprite;
resources.js
(function() {
var resourceCache = {};
var loading = [];
var readyCallbacks = [];
// Load an image url or an array of image urls
function load(urlOrArr) {
if(urlOrArr instanceof Array) {
urlOrArr.forEach(function(url) {
_load(url);
});
}
else {
_load(urlOrArr);
}
}
function _load(url) {
if(resourceCache[url]) {
return resourceCache[url];
}
else {
var img = new Image();
img.onload = function() {
resourceCache[url] = img;
if(isReady()) {
readyCallbacks.forEach(function(func) { func(); });
}
};
resourceCache[url] = false;
img.src = url;
}
}
function get(url) {
return resourceCache[url];
}
function isReady() {
var ready = true;
for(var k in resourceCache) {
if(resourceCache.hasOwnProperty(k) &&
!resourceCache[k]) {
ready = false;
}
}
return ready;
}
function onReady(func) {
readyCallbacks.push(func);
}
window.resources = {
load: load,
get: get,
onReady: onReady,
isReady: isReady
};
input.js
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
apps.js
// A cross-browser requestAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = (now - lastTime) / 1000.0;
update(dt);
render();
lastTime = now;
requestAnimFrame(main);
};
function init() {
terrainPattern = ctx.createPattern(resources.get('terrain.png'), 'repeat');
document.getElementById('play-again').addEventListener('click', function() {
reset();
});
reset();
lastTime = Date.now();
main();
}
resources.load([
'sprites.png',
'terrain.png'
]);
resources.onReady(init);
// Game state
var player = {
pos: [0, 0],
sprite: new Sprite('sprites.png', [0, 0], [39, 39], 16, [0, 1])
};
var bullets = [];
var enemies = [];
var explosions = [];
var lastFire = Date.now();
var gameTime = 0;
var isGameOver;
var terrainPattern;
var score = 0;
var scoreEl = document.getElementById('score');
// Speed in pixels per second
var playerSpeed = 200;
var bulletSpeed = 500;
var enemySpeed = 100;
// Update game objects
function update(dt) {
gameTime += dt;
handleInput(dt);
updateEntities(dt);
// It gets harder over time by adding enemies using this
// equation: 1-.993^gameTime
if(Math.random() < 1 - Math.pow(.993, gameTime)) {
enemies.push({
pos: [canvas.width,
Math.random() * (canvas.height - 39)],
sprite: new Sprite('sprites.png', [0, 78], [80, 39],
6, [0, 1, 2, 3, 2, 1])
});
}
checkCollisions();
scoreEl.innerHTML = score;
};
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
if(input.isDown('SPACE') && !isGameOver && Date.now() - lastFire > 100) {
var x = player.pos[0] + player.sprite.size[0] / 2;
var y = player.pos[1] + player.sprite.size[1] / 2;
bullets.push({ pos: [x, y],
dir: 'forward',
sprite: new Sprite('sprites.png', [0, 39], [18, 8]) });
bullets.push({ pos: [x, y],
dir: 'up',
sprite: new Sprite('sprites.png', [0, 50], [9, 5]) });
bullets.push({ pos: [x, y],
dir: 'down',
sprite: new Sprite('sprites.png', [0, 60], [9, 5]) });
lastFire = Date.now();
}
}
function updateEntities(dt) {
// Update the player sprite animation
player.sprite.update(dt);
// Update all the bullets
for(var i=0; i<bullets.length; i++) {
var bullet = bullets[i];
switch(bullet.dir) {
case 'up': bullet.pos[1] -= bulletSpeed * dt; break;
case 'down': bullet.pos[1] += bulletSpeed * dt; break;
default:
bullet.pos[0] += bulletSpeed * dt;
}
// Remove the bullet if it goes offscreen
if(bullet.pos[1] < 0 || bullet.pos[1] > canvas.height ||
bullet.pos[0] > canvas.width) {
bullets.splice(i, 1);
i--;
}
}
// Update all the enemies
for(var i=0; i<enemies.length; i++) {
enemies[i].pos[0] -= enemySpeed * dt;
enemies[i].sprite.update(dt);
// Remove if offscreen
if(enemies[i].pos[0] + enemies[i].sprite.size[0] < 0) {
enemies.splice(i, 1);
i--;
}
}
// Update all the explosions
for(var i=0; i<explosions.length; i++) {
explosions[i].sprite.update(dt);
// Remove if animation is done
if(explosions[i].sprite.done) {
explosions.splice(i, 1);
i--;
}
}
}
// Collisions
function collides(x, y, r, b, x2, y2, r2, b2) {
return !(r <= x2 || x > r2 ||
b <= y2 || y > b2);
}
function boxCollides(pos, size, pos2, size2) {
return collides(pos[0], pos[1],
pos[0] + size[0], pos[1] + size[1],
pos2[0], pos2[1],
pos2[0] + size2[0], pos2[1] + size2[1]);
}
function checkCollisions() {
checkPlayerBounds();
// Run collision detection for all enemies and bullets
for(var i=0; i<enemies.length; i++) {
var pos = enemies[i].pos;
var size = enemies[i].sprite.size;
for(var j=0; j<bullets.length; j++) {
var pos2 = bullets[j].pos;
var size2 = bullets[j].sprite.size;
if(boxCollides(pos, size, pos2, size2)) {
// Remove the enemy
enemies.splice(i, 1);
i--;
// Add score
score += 100;
// Add an explosion
explosions.push({
pos: pos,
sprite: new Sprite('sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
// Remove the bullet and stop this iteration
bullets.splice(j, 1);
break;
}
}
if(boxCollides(pos, size, player.pos, player.sprite.size)) {
gameOver();
}
}
}
function checkPlayerBounds() {
// Check bounds
if(player.pos[0] < 0) {
player.pos[0] = 0;
}
else if(player.pos[0] > canvas.width - player.sprite.size[0]) {
player.pos[0] = canvas.width - player.sprite.size[0];
}
if(player.pos[1] < 0) {
player.pos[1] = 0;
}
else if(player.pos[1] > canvas.height - player.sprite.size[1]) {
player.pos[1] = canvas.height - player.sprite.size[1];
}
}
// Draw everything
function render() {
ctx.fillStyle = terrainPattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Render the player if the game isn't over
if(!isGameOver) {
renderEntity(player);
}
renderEntities(bullets);
renderEntities(enemies);
renderEntities(explosions);
};
function renderEntities(list) {
for(var i=0; i<list.length; i++) {
renderEntity(list[i]);
}
}
function renderEntity(entity) {
ctx.save();
ctx.translate(entity.pos[0], entity.pos[1]);
entity.sprite.render(ctx);
ctx.restore();
}
// Game over
function gameOver() {
document.getElementById('game-over').style.display = 'block';
document.getElementById('game-over-overlay').style.display = 'block';
isGameOver = true;
}
// Reset game to original state
function reset() {
document.getElementById('game-over').style.display = 'none';
document.getElementById('game-over-overlay').style.display = 'none';
isGameOver = false;
gameTime = 0;
score = 0;
enemies = [];
bullets = [];
player.pos = [50, canvas.height / 2];
app.css
html, body {
margin: 0;
padding: 0;
background-color: #151515;
}
canvas {
display: block;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper {
width: 512px;
margin: 0 auto;
margin-top: 2em;
}
#instructions {
float: left;
font-family: sans-serif;
color: #757575;
}
#score {
float: right;
color: white;
font-size: 2em;
}
.key {
color: #aaffdd;
}
#game-over, #game-over-overlay {
margin: auto;
width: 512px;
height: 480px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#game-over-overlay {
background-color: black;
opacity: .5;
}
#game-over {
height: 200px;
text-align: center;
color: white;
}
#game-over h1 {
font-size: 3em;
font-family: sans-serif;
}
#game-over button {
font-size: 1.5em;
}
Here is the original game link
http://jlongster.com/Making-Sprite-based-Games-with-Canvas
If someone could put up a fiddle to see why it is not working it would be most appreciated.
Errors from the console
Uncaught SyntaxError: Unexpected end of input resources.js:61
Uncaught SyntaxError: Unexpected end of input input.js:43
Uncaught SyntaxError: Unexpected end of input sprite.js:54
Uncaught SyntaxError: Unexpected end of input app.js:302
Are you running this on a webserver? The way that you phrased it makes me think you you downloaded those files and just double-clicked index.html.
You need to download something like https://www.apachefriends.org/index.html and start the Apache service up, then put your files in the /xampp/htdocs/ folder... then goto
http://localhost/index.html
to get it to load.