I have a script that is working fine but can take a lot of time to complete.
This is a javascript document and runs several functions.
This script runs within InDesign and is javascript based. The ExtendScript Toolkit provides several demoscripts and one of them is SnpCreateProgressBar.jsx.
Now I want to add the progressbar to my current script but I'm not entirely sure how to do this.
Without posting the entire code here I'll do a function. This is repeated throughout the script.
var myDoc = app.activeDocument;
var myTables = myDoc.stories.everyItem().tables.everyItem();
var myTableElements = myTables.getElements();
function basicSearchReplace(findWhat, changeTo){
app.findGrepPreferences = app.changeGrepPreferences = null;
app.findChangeGrepOptions = NothingEnum.nothing;
app.findGrepPreferences.findWhat = findWhat;
app.changeGrepPreferences.changeTo = changeTo;
myDoc.changeGrep();
}
basicSearchReplace ('^~8 ', '~8\\t');
basicSearchReplace ('^·( |\\t)', '~8\\t');
The SnpCreateProgressBar.jsx can be found here
Maybe there is another extendscript way to create a progress bar?
--- Small Update ---
So after some Googeling and testing I came up with :
function SnpCreateProgressBar ()
{
this.windowRef = null;
}
SnpCreateProgressBar.prototype.run = function() {
var win = new Window("palette", "SnpCreateProgressBar", [150, 150, 600, 260]);
win.pnl = win.add("panel", [10, 10, 440, 100], "Script Progress");
win.pnl.progBar = win.pnl.add("progressbar", [20, 35, 410, 60], 0, 100);
win.pnl.progBarLabel = win.pnl.add("statictext", [20, 20, 320, 35], "0%");
win.show();
while(win.pnl.progBar.value < win.pnl.progBar.maxvalue)
{
// this is what causes the progress bar increase its progress
win.pnl.progBar.value++;
win.pnl.progBarLabel.text = win.pnl.progBar.value+"%";
$.sleep(10);
}
alert('Done!');
win.close();
};
if(typeof(SnpCreateProgressBar_unitTest) == "undefined") {
new SnpCreateProgressBar().run();
}
Now I don't think I fully understand.
If I place my "to-run" code in the while loop it just executes that and runs the process bar at the end... Same goes for the if-loop at the bottom
What am I not understanding?
See this ProgressBar implementation. I use it all the time :
https://github.com/indiscripts/extendscript/blob/master/scriptui/ProgressBar.jsx
/*******************************************************************************
Name: ProgressBar
Desc: Simple progress bar.
Path: /inc/progress.lib.jsxinc
Require: ---
Encoding: ÛȚF8
Kind: Constructor
API: show()=reset() msg() hit() hitValue() hide() close()
DOM-access: NO (ScriptUI)
Todo: Does not work in Mac El Capitan
Created: 141112 (YYMMDD)
Modified: 160228 (YYMMDD)
*******************************************************************************/
$.hasOwnProperty('ProgressBar')||(function(H/*OST*/,S/*ELF*/,I/*NNER*/)
{
H[S] = function ProgressBar(/*str*/title,/*uint*/width,/*uint*/height)
{
(60<=(width||0))||(width=340);
(40<=(height||0))||(height=60);
var H = 22,
Y = (3*height-2*H)>>2,
W = new Window('palette', ' '+title, [0,0,width,height]),
P = W.add('progressbar', { x:20, y:height>>2, width:width-40, height:12 }, 0,100),
T = W.add('statictext' , { x:0, y:Y, width:width, height:H }),
__ = function(a,b){ return localize.apply(null,a.concat(b)) };
this.pattern = ['%1'];
W.center();
// ---
// API
// ---
this.msg = function(/*str*/s, v)
// ---------------------------------
{
s && (T.location = [(width-T.graphics.measureString(s)[0])>>1, Y]);
T.text = s;
W.update();
};
this.show = this.reset = function(/*str*/s, /*uint*/v)
// ---------------------------------
{
if( s && s != localize(s,1,2,3,4,5,6,7,8,9) )
{
this.pattern[0] = s;
s = __(this.pattern, [].slice.call(arguments,2));
}
else
{
this.pattern[0] = '%1';
}
P.value = 0;
P.maxvalue = v||0;
P.visible = !!v;
this.msg(s);
W.show();
W.update();
};
this.hit = function(x)
// ---------------------------------
{
++P.value;
('undefined' != typeof x) && this.msg(__(this.pattern, [].slice.call(arguments,0)));
W.update();
};
this.hitValue = function(v,x)
// ---------------------------------
{
P.value = v;
('undefined' != typeof x) && this.msg(__(this.pattern, [].slice.call(arguments,1)));
W.update();
};
this.hide = function()
// ---------------------------------
{
W.hide();
};
this.close = function()
// ---------------------------------
{
W.close();
};
};
})($,{toString:function(){return 'ProgressBar'}},{});
Sample code:
//------------------------------------------------
// SAMPLE CODE
//------------------------------------------------
(function()
{
var PB = new $.ProgressBar("Script Title",350,100),
i, vMax;
// Quick process
// ---
PB.show("Processing quickly... %1 / 500", vMax=500, i=0);
for( ; i < vMax ; $.sleep(8), PB.hit(++i) );
PB.reset("Wait for 800 ms...");
$.sleep(800);
// Slow process
// ---
PB.reset("And now slowly (%1%) | Stage %2", vMax=13, 0, i=0);
for( ; i < vMax ; ++i, PB.hit((100*(i/vMax)).toFixed(2), i), $.sleep(400+200*(.5-Math.random())) );
$.sleep(500);
PB.msg("The job is done.");
$.sleep(1500);
// Quit
// ---
PB.close();
})();
Related
I built an interface that calls a web API in asp.net (i use c# and javascript/ajax to implement that).
The client side call to the controller, the controller needs to create animation gif and send it back to the client side by a string of base64 or byte array, when the client side gets the base64 he should display it into a canvas.
Now the problem is that the canvas display only the first frame of the animation gif like a static image.
I already read a lot on the internet and find this:
How Do I Convert A GIF Animation To Base64 String And Back To A GIF Animation?
But it's not helped me because I don't want to save the image on the disc just to display it on the client side.
*Note that when I save the image from server side on my disc its save it as gif and display all frames together like I wish, something wrong when I transfer it to client side.
*I use ImageMagick to create the animated gif.
Here is my client side code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top: 20px;">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<!---->
<canvas id="canvasImage" width="564" height="120">
<p>We apologize, your browser does not support canvas at this time!</p>
</canvas>
<!---->
</div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/api/EngineProccess',
method: 'GET',
success: function (data) {
var imageObj = new Image();
var canvas = document.getElementById("canvasImage");
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function () {
context.drawImage(image, 0, 0);
};
console.log(data);
image.src = "data:image/gif;base64," + data;
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
</script>
</body>
</html>
and here is the server code:
public class EngineProccessController : ApiController
{
// GET api/EngineProccess
public String Get()
{
using (MagickImageCollection collection = new MagickImageCollection())
{
// Add first image and set the animation delay to 100ms
collection.Add("Snakeware1.gif");
collection[0].AnimationDelay = 100;
// Add second image, set the animation delay to 100ms and flip the image
collection.Add("Snakeware2.gif");
collection[1].AnimationDelay = 100;
collection[1].Flip();
// Optionally reduce colors
QuantizeSettings settings = new QuantizeSettings();
settings.Colors = 256;
collection.Quantize(settings);
// Optionally optimize the images (images should have the same size).
collection.Optimize();
// Save gif
//collection.Write("D://Test01//Test01//Animated.gif");
string data = collection.ToBase64();
return data;
}
}
}
Any ideas?
Please help.
Edit: after some days i found the problem, i use magicimage (magic.net) to create the gif animaited, the base64 was ok but the problem was in the canvas element, the canvas didnt display the animation likei want so i changed the element canvas to be an regular image element () and the changed the src of the image dynamic.
Regards,
Jr.Rafa
Example loading playing gif on canvas.
Sorry but just under 30K answer limit, code and comment very cut down to fit. Ask in comments if needed. See bottom of snippet on basic usage.
/*
The code was created as to the specifications set out in https://www.w3.org/Graphics/GIF/spec-gif89a.txt
The document states usage conditions
"The Graphics Interchange Format(c) is the Copyright property of
CompuServe Incorporated. GIF(sm) is a Service Mark property of
CompuServe Incorporated."
https://en.wikipedia.org/wiki/GIF#Unisys_and_LZW_patent_enforcement last paragraph
Additional sources
https://en.wikipedia.org/wiki/GIF
https://www.w3.org/Graphics/GIF/spec-gif87.txt
*/
var GIF = function () {
var timerID;
var st;
var interlaceOffsets = [0, 4, 2, 1]; // used in de-interlacing.
var interlaceSteps = [8, 8, 4, 2];
var interlacedBufSize = undefined;
var deinterlaceBuf = undefined;
var pixelBufSize = undefined;
var pixelBuf = undefined;
const GIF_FILE = {
GCExt : 0xF9,
COMMENT : 0xFE,
APPExt : 0xFF,
UNKNOWN : 0x01,
IMAGE : 0x2C,
EOF : 59,
EXT : 0x21,
};
var Stream = function (data) { // simple buffered stream
this.data = new Uint8ClampedArray(data);
this.pos = 0;
var len = this.data.length;
this.getString = function (count) {
var s = "";
while (count--) {
s += String.fromCharCode(this.data[this.pos++]);
}
return s;
};
this.readSubBlocks = function () {
var size, count, data;
data = "";
do {
count = size = this.data[this.pos++];
while (count--) {
data += String.fromCharCode(this.data[this.pos++]);
}
} while (size !== 0 && this.pos < len);
return data;
}
this.readSubBlocksB = function () { // reads a set of blocks as binary
var size, count, data;
data = [];
do {
count = size = this.data[this.pos++];
while (count--) {
data.push(this.data[this.pos++]);
}
} while (size !== 0 && this.pos < len);
return data;
}
};
// LZW decoder uncompressed each frame's pixels
var lzwDecode = function (minSize, data) {
var i, pixelPos, pos, clear, eod, size, done, dic, code, last, d, len;
pos = 0;
pixelPos = 0;
dic = [];
clear = 1 << minSize;
eod = clear + 1;
size = minSize + 1;
done = false;
while (!done) {
last = code;
code = 0;
for (i = 0; i < size; i++) {
if (data[pos >> 3] & (1 << (pos & 7))) {
code |= 1 << i;
}
pos++;
}
if (code === clear) { // clear and reset the dictionary
dic = [];
size = minSize + 1;
for (i = 0; i < clear; i++) {
dic[i] = [i];
}
dic[clear] = [];
dic[eod] = null;
continue;
}
if (code === eod) { // end of data
done = true;
return;
}
if (code >= dic.length) {
dic.push(dic[last].concat(dic[last][0]));
} else
if (last !== clear) {
dic.push(dic[last].concat(dic[code][0]));
}
d = dic[code];
len = d.length;
for (i = 0; i < len; i++) {
pixelBuf[pixelPos++] = d[i];
}
if (dic.length === (1 << size) && size < 12) {
size++;
}
}
};
var parseColourTable = function (count) { // get a colour table of length count
// Each entry is 3 bytes, for RGB.
var colours = [];
for (var i = 0; i < count; i++) {
colours.push([st.data[st.pos++], st.data[st.pos++], st.data[st.pos++]]);
}
return colours;
};
var parse = function () { // read the header. This is the starting point of the decode and async calls parseBlock
var bitField;
st.pos += 6; // skip the first stuff see GifEncoder for details
gif.width = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
gif.height = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
bitField = st.data[st.pos++];
gif.colorRes = (bitField & 0b1110000) >> 4;
gif.globalColourCount = 1 << ((bitField & 0b111) + 1);
gif.bgColourIndex = st.data[st.pos++];
st.pos++; // ignoring pixel aspect ratio. if not 0, aspectRatio = (pixelAspectRatio + 15) / 64
if (bitField & 0b10000000) { // global colour flag
gif.globalColourTable = parseColourTable(gif.globalColourCount);
}
setTimeout(parseBlock, 0);
};
var parseAppExt = function () { // get application specific data. Netscape added iterations and terminator. Ignoring that
st.pos += 1;
if ('NETSCAPE' === st.getString(8)) {
st.pos += 8; // ignoring this data. iterations (word) and terminator (byte)
} else {
st.pos += 3; // 3 bytes of string usually "2.0" when identifier is NETSCAPE
st.readSubBlocks(); // unknown app extension
}
};
var parseGCExt = function () { // get GC data
var bitField;
st.pos++;
bitField = st.data[st.pos++];
gif.disposalMethod = (bitField & 0b11100) >> 2;
gif.transparencyGiven = bitField & 0b1 ? true : false; // ignoring bit two that is marked as userInput???
gif.delayTime = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
gif.transparencyIndex = st.data[st.pos++];
st.pos++;
};
var parseImg = function () { // decodes image data to create the indexed pixel image
var deinterlace, frame, bitField;
deinterlace = function (width) { // de interlace pixel data if needed
var lines, fromLine, pass, toline;
lines = pixelBufSize / width;
fromLine = 0;
if (interlacedBufSize !== pixelBufSize) {
deinterlaceBuf = new Uint8Array(pixelBufSize);
interlacedBufSize = pixelBufSize;
}
for (pass = 0; pass < 4; pass++) {
for (toLine = interlaceOffsets[pass]; toLine < lines; toLine += interlaceSteps[pass]) {
deinterlaceBuf.set(pixelBuf.subArray(fromLine, fromLine + width), toLine * width);
fromLine += width;
}
}
};
frame = {}
gif.frames.push(frame);
frame.disposalMethod = gif.disposalMethod;
frame.time = gif.length;
frame.delay = gif.delayTime * 10;
gif.length += frame.delay;
if (gif.transparencyGiven) {
frame.transparencyIndex = gif.transparencyIndex;
} else {
frame.transparencyIndex = undefined;
}
frame.leftPos = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
frame.topPos = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
frame.width = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
frame.height = (st.data[st.pos++]) + ((st.data[st.pos++]) << 8);
bitField = st.data[st.pos++];
frame.localColourTableFlag = bitField & 0b10000000 ? true : false;
if (frame.localColourTableFlag) {
frame.localColourTable = parseColourTable(1 << ((bitField & 0b111) + 1));
}
if (pixelBufSize !== frame.width * frame.height) { // create a pixel buffer if not yet created or if current frame size is different from previous
pixelBuf = new Uint8Array(frame.width * frame.height);
pixelBufSize = frame.width * frame.height;
}
lzwDecode(st.data[st.pos++], st.readSubBlocksB()); // decode the pixels
if (bitField & 0b1000000) { // de interlace if needed
frame.interlaced = true;
deinterlace(frame.width);
} else {
frame.interlaced = false;
}
processFrame(frame); // convert to canvas image
};
var processFrame = function (frame) {
var ct, cData, dat, pixCount, ind, useT, i, pixel, pDat, col, frame, ti;
frame.image = document.createElement('canvas');
frame.image.width = gif.width;
frame.image.height = gif.height;
frame.image.ctx = frame.image.getContext("2d");
ct = frame.localColourTableFlag ? frame.localColourTable : gif.globalColourTable;
if (gif.lastFrame === null) {
gif.lastFrame = frame;
}
useT = (gif.lastFrame.disposalMethod === 2 || gif.lastFrame.disposalMethod === 3) ? true : false;
if (!useT) {
frame.image.ctx.drawImage(gif.lastFrame.image, 0, 0, gif.width, gif.height);
}
cData = frame.image.ctx.getImageData(frame.leftPos, frame.topPos, frame.width, frame.height);
ti = frame.transparencyIndex;
dat = cData.data;
if (frame.interlaced) {
pDat = deinterlaceBuf;
} else {
pDat = pixelBuf;
}
pixCount = pDat.length;
ind = 0;
for (i = 0; i < pixCount; i++) {
pixel = pDat[i];
col = ct[pixel];
if (ti !== pixel) {
dat[ind++] = col[0];
dat[ind++] = col[1];
dat[ind++] = col[2];
dat[ind++] = 255; // Opaque.
} else
if (useT) {
dat[ind + 3] = 0; // Transparent.
ind += 4;
} else {
ind += 4;
}
}
frame.image.ctx.putImageData(cData, frame.leftPos, frame.topPos);
gif.lastFrame = frame;
if (!gif.waitTillDone && typeof gif.onload === "function") { // if !waitTillDone the call onload now after first frame is loaded
doOnloadEvent();
}
};
var finnished = function () { // called when the load has completed
gif.loading = false;
gif.frameCount = gif.frames.length;
gif.lastFrame = null;
st = undefined;
gif.complete = true;
gif.disposalMethod = undefined;
gif.transparencyGiven = undefined;
gif.delayTime = undefined;
gif.transparencyIndex = undefined;
gif.waitTillDone = undefined;
pixelBuf = undefined; // dereference pixel buffer
deinterlaceBuf = undefined; // dereference interlace buff (may or may not be used);
pixelBufSize = undefined;
deinterlaceBuf = undefined;
gif.currentFrame = 0;
if (gif.frames.length > 0) {
gif.image = gif.frames[0].image;
}
doOnloadEvent();
if (typeof gif.onloadall === "function") {
(gif.onloadall.bind(gif))({
type : 'loadall',
path : [gif]
});
}
if (gif.playOnLoad) {
gif.play();
}
}
var canceled = function () { // called if the load has been cancelled
finnished();
if (typeof gif.cancelCallback === "function") {
(gif.cancelCallback.bind(gif))({
type : 'canceled',
path : [gif]
});
}
}
var parseExt = function () { // parse extended blocks
switch (st.data[st.pos++]) {
case GIF_FILE.GCExt:
parseGCExt();
break;
case GIF_FILE.COMMENT:
gif.comment += st.readSubBlocks(); // found a comment field
break;
case GIF_FILE.APPExt:
parseAppExt();
break;
case GIF_FILE.UNKNOWN: // not keeping this data
st.pos += 13; // deliberate fall through to default
default: // not keeping this if it happens
st.readSubBlocks();
break;
}
}
var parseBlock = function () { // parsing the blocks
if (gif.cancel !== undefined && gif.cancel === true) {
canceled();
return;
}
switch (st.data[st.pos++]) {
case GIF_FILE.IMAGE: // image block
parseImg();
if (gif.firstFrameOnly) {
finnished();
return;
}
break;
case GIF_FILE.EOF: // EOF found so cleanup and exit.
finnished();
return;
case GIF_FILE.EXT: // extend block
default:
parseExt();
break;
}
if (typeof gif.onprogress === "function") {
gif.onprogress({
bytesRead : st.pos,
totalBytes : st.data.length,
frame : gif.frames.length
});
}
setTimeout(parseBlock, 0);
};
var cancelLoad = function (callback) {
if (gif.complete) {
return false;
}
gif.cancelCallback = callback;
gif.cancel = true;
return true;
}
var error = function (type) {
if (typeof gif.onerror === "function") {
(gif.onerror.bind(this))({
type : type,
path : [this]
});
}
gif.onerror = undefined;
gif.onload = undefined;
gif.loading = false;
}
var doOnloadEvent = function () { // fire onload event if set
gif.currentFrame = 0;
gif.lastFrameAt = new Date().valueOf();
gif.nextFrameAt = new Date().valueOf();
if (typeof gif.onload === "function") {
(gif.onload.bind(gif))({
type : 'load',
path : [gif]
});
}
gif.onload = undefined;
gif.onerror = undefined;
}
var dataLoaded = function (data) {
st = new Stream(data);
parse();
}
var loadGif = function (filename) { // starts the load
var ajax = new XMLHttpRequest();
ajax.responseType = "arraybuffer";
ajax.onload = function (e) {
if (e.target.status === 400) {
error("Bad Request response code");
} else if (e.target.status === 404) {
error("File not found");
} else {
dataLoaded(ajax.response);
}
};
ajax.open('GET', filename, true);
ajax.send();
ajax.onerror = function (e) {
error("File error");
};
this.src = filename;
this.loading = true;
}
function play() { // starts play if paused
if (!gif.playing) {
gif.paused = false;
gif.playing = true;
playing();
}
}
function pause() { // stops play
gif.paused = true;
gif.playing = false;
clearTimeout(timerID);
}
function togglePlay(){
if(gif.paused || !gif.playing){
gif.play();
}else{
gif.pause();
}
}
function seekFrame(frame) { // seeks to frame number.
clearTimeout(timerID);
frame = frame < 0 ? (frame % gif.frames.length) + gif.frames.length : frame;
gif.currentFrame = frame % gif.frames.length;
if (gif.playing) {
playing();
} else {
gif.image = gif.frames[gif.currentFrame].image;
}
}
function seek(time) { // time in Seconds
clearTimeout(timerID);
if (time < 0) {
time = 0;
}
time *= 1000; // in ms
time %= gif.length;
var frame = 0;
while (time > gif.frames[frame].time + gif.frames[frame].delay && frame < gif.frames.length) {
frame += 1;
}
gif.currentFrame = frame;
if (gif.playing) {
playing();
} else {
gif.image = gif.frames[gif.currentFrame].image;
}
}
function playing() {
var delay;
var frame;
if (gif.playSpeed === 0) {
gif.pause();
return;
}
if (gif.playSpeed < 0) {
gif.currentFrame -= 1;
if (gif.currentFrame < 0) {
gif.currentFrame = gif.frames.length - 1;
}
frame = gif.currentFrame;
frame -= 1;
if (frame < 0) {
frame = gif.frames.length - 1;
}
delay = -gif.frames[frame].delay * 1 / gif.playSpeed;
} else {
gif.currentFrame += 1;
gif.currentFrame %= gif.frames.length;
delay = gif.frames[gif.currentFrame].delay * 1 / gif.playSpeed;
}
gif.image = gif.frames[gif.currentFrame].image;
timerID = setTimeout(playing, delay);
}
var gif = { // the gif image object
onload : null, // fire on load. Use waitTillDone = true to have load fire at end or false to fire on first frame
onerror : null, // fires on error
onprogress : null, // fires a load progress event
onloadall : null, // event fires when all frames have loaded and gif is ready
paused : false, // true if paused
playing : false, // true if playing
waitTillDone : true, // If true onload will fire when all frames loaded, if false, onload will fire when first frame has loaded
loading : false, // true if still loading
firstFrameOnly : false, // if true only load the first frame
width : null, // width in pixels
height : null, // height in pixels
frames : [], // array of frames
comment : "", // comments if found in file. Note I remember that some gifs have comments per frame if so this will be all comment concatenated
length : 0, // gif length in ms (1/1000 second)
currentFrame : 0, // current frame.
frameCount : 0, // number of frames
playSpeed : 1, // play speed 1 normal, 2 twice 0.5 half, -1 reverse etc...
lastFrame : null, // temp hold last frame loaded so you can display the gif as it loads
image : null, // the current image at the currentFrame
playOnLoad : true, // if true starts playback when loaded
// functions
load : loadGif, // call this to load a file
cancel : cancelLoad, // call to stop loading
play : play, // call to start play
pause : pause, // call to pause
seek : seek, // call to seek to time
seekFrame : seekFrame, // call to seek to frame
togglePlay : togglePlay, // call to toggle play and pause state
};
return gif;
}
/*=================================================================
USEAGE Example below
Image used from Wiki see HTML for requiered image atribution
===================================================================*/
const ctx = canvas.getContext("2d");
ctx.font = "16px arial";
var changeFrame = false;
var changeSpeed = false;
frameNum.addEventListener("mousedown",()=>{changeFrame = true ; changeSpeed = false});
speedInput.addEventListener("mousedown",()=>{changeSpeed = true; changeFrame = false});
const gifSrc = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Odessa_TX_Oil_Well_with_Lufkin_320D_pumping_unit.gif/220px-Odessa_TX_Oil_Well_with_Lufkin_320D_pumping_unit.gif"
var myGif = GIF(); // Creates a new gif
myGif.load(gifSrc); // set URL and load
myGif.onload = function(event){ // fires when loading is complete
frameNum.max = myGif.frameCount-1;
animate();
}
myGif.onprogress = function(event){ // Note this function is not bound to myGif
if(canvas.width !== myGif.width || canvas.height !== myGif.height){
canvas.width = myGif.width;
canvas.height = myGif.height;
ctx.font = "16px arial";
}
if(myGif.lastFrame !== null){
ctx.drawImage(myGif.lastFrame.image,0,0);
}
ctx.fillStyle = "black";
ctx.fillText("Loaded frame "+event.frame,8,20);
frameNum.max = event.frame-1;
frameNum.value = event.frame;
frameText.textContent = frameNum.value + "/" + (frameNum.max-1);
}
myGif.onerror = function(event){
ctx.fillStyle = "black";
ctx.fillText("Could not load the Gif ",8,20);
ctx.fillText("Error : " + event.type,8,40);
}
function animate(){
if(changeFrame){
if(myGif.playing){
myGif.pause();
}
myGif.seekFrame(Number(frameNum.value));
}else if(changeSpeed){
myGif.playSpeed = speedInput.value;
if(myGif.paused){
myGif.play();
}
}
frameNum.value = myGif.currentFrame;
frameText.textContent = frameNum.value + "/" + frameNum.max;
if(myGif.paused){
speedInput.value = 0;
}else{
speedInput.value = myGif.playSpeed;
}
speedText.textContent = speedInput.value;
ctx.drawImage(myGif.image,0,0);
requestAnimationFrame(animate);
}
canvas { border : 2px solid black; }
p { font-family : arial; font-size : 12px }
<canvas id="canvas"></canvas>
<div id="inputs">
<input id="frameNum" type = "range" min="0" max="1" step="1" value="0"></input>
Frame : <span id="frameText"></span><br>
<input id="speedInput" type = "range" min="-3" max="3" step="0.1" value="1"></input>
Speed : <span id="speedText"></span><br>
</div>
<p>Image source <br>By DASL51984 - Original YouTube video by user "derekdz", looped by DASL51984, CC BY-SA 4.0, Link</p>
I am trying to implement Range slider plugin to my video js player in my react project. I am already markers plugin integrated to my player. I have see the documentation of Rangeslider Plugin and followed the instructions given https://github.com/iamjem/rangeslider-videojs , couldn't get it working. When I do it, neither I get rangeslider on my player nor I get markers (which were working before adding rangeslider). Here is my code.
PlayerLogic.js (I initailize my player in this)
class PlayerLogic extends Component {
constructor() {
super();
this.state = {
player: {}
};
}
componentDidMount() {
var self = this;
var player = videojs(this.refs.video, this.props.options).ready(function () {
self.player = this;
self.player.on('play', self.handlePlay);
});
if (this.props.onPlayerInit) this.props.onPlayerInit(player);
var options = {};
player.rangeslider(options);
player.markers({
markerStyle: {},
markers: [
{length: 8, startTime: 10, endTime: 15, time: 9.5, text: "Cigarette"},
{length: 2, startTime: 20, endTime: 25, time: 16, text: "Cigarette"},
{length: 15, startTime: 30, endTime: 38, time: 23.6, text: "Cigarette"},
{length: 11, startTime: 30, endTime: 38, time: 23.6, text: "Alcohol"},
{length: 25, startTime: 51, endTime: 55, time: 28, text: "Cigarette"},
{length: 10, startTime: 60, endTime: 80, time: 35, text: "Alcohol"},
{length: 15, startTime: 70, endTime: 115, time: 50, text: "Alcohol"},
],
onMarkerReached: function () {
player.pause();
},
});
this.setState({player: player});
}
handlePlay() {
console.log("handle play ")
}
render() {
var props = blacklist(this.props, 'children', 'className', 'src', 'type', 'onPlay');
props.className = cx(this.props.className, 'videojs', 'video-js vjs-default-skin', 'vjs-big-play-centered');
assign(props, {
ref: 'video',
controls: true,
width: "700", height: "450"
});
return (
<div>
<video {... props}>
<source src={this.props.src} type={this.props.type} id={this.props.id}/>
</video>
</div>)
}
}
part of rangeslider.js (as the actual code is too long)
//----------------Load Plugin----------------//
(function () {
//-- Load RangeSlider plugin in videojs
function RangeSlider(options) {
player.rangeslider = new RangeSlider(player, options);
//When the DOM and the video media is loaded
function initialVideoFinished(event) {
var plugin = player.rangeslider;
//All components will be initialize after they have been loaded by videojs
for (var index in plugin.components) {
plugin.components[index].init_();
}
if (plugin.options.hidden)
plugin.hide(); //Hide the Range Slider
if (plugin.options.locked)
plugin.lock(); //Lock the Range Slider
if (plugin.options.panel == false)
plugin.hidePanel(); //Hide the second Panel
if (plugin.options.controlTime == false)
plugin.hidecontrolTime(); //Hide the control time panel
plugin._reset();
player.trigger('loadedRangeSlider'); //Let know if the Range Slider DOM is ready
}
if (player.techName == 'Youtube') {
//Detect youtube problems
player.one('error', function (e) {
switch (player.error) {
case 2:
alert("The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.");
case 5:
alert("The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.");
case 100:
alert("The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.");
break;
case 101:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
case 150:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
default:
alert("Unknown Error");
break;
}
});
player.on('firstplay', initialVideoFinished);
} else {
player.one('playing', initialVideoFinished);
}
console.log("Loaded Plugin RangeSlider");
}
videojs.plugin('rangeslider', RangeSlider);
//-- Plugin
function RangeSlider(player, options) {
var player = player || this;
this.player = player;
this.components = {}; // holds any custom components we add to the player
options = options || {}; // plugin options
if (!options.hasOwnProperty('locked'))
options.locked = false; // lock slider handles
if (!options.hasOwnProperty('hidden'))
options.hidden = true; // hide slider handles
if (!options.hasOwnProperty('panel'))
options.panel = true; // Show Second Panel
if (!options.hasOwnProperty('controlTime'))
options.controlTime = true; // Show Control Time to set the arrows in the edition
this.options = options;
this.init();
}
//-- Methods
RangeSlider.prototype = {
/*Constructor*/
init: function () {
var player = this.player || {};
this.updatePrecision = 3;
//position in second of the arrows
this.start = 0;
this.end = 0;
//components of the plugin
var controlBar = player.controlBar;
var seekBar = controlBar.progressControl.seekBar;
this.components.RSTimeBar = seekBar.RSTimeBar;
this.components.ControlTimePanel = controlBar.ControlTimePanel;
//Save local component
this.rstb = this.components.RSTimeBar;
this.box = this.components.SeekRSBar = this.rstb.SeekRSBar;
this.bar = this.components.SelectionBar = this.box.SelectionBar;
this.left = this.components.SelectionBarLeft = this.box.SelectionBarLeft;
this.right = this.components.SelectionBarRight = this.box.SelectionBarRight;
this.tp = this.components.TimePanel = this.box.TimePanel;
this.tpl = this.components.TimePanelLeft = this.tp.TimePanelLeft;
this.tpr = this.components.TimePanelRight = this.tp.TimePanelRight;
this.ctp = this.components.ControlTimePanel;
this.ctpl = this.components.ControlTimePanelLeft = this.ctp.ControlTimePanelLeft;
this.ctpr = this.components.ControlTimePanelRight = this.ctp.ControlTimePanelRight;
},
lock: function () {
this.options.locked = true;
this.ctp.enable(false);
if (typeof this.box != 'undefined')
videojs.addClass(this.box.el_, 'locked');
},
unlock: function () {
this.options.locked = false;
this.ctp.enable();
if (typeof this.box != 'undefined')
videojs.removeClass(this.box.el_, 'locked');
},
show: function () {
this.options.hidden = false;
if (typeof this.rstb != 'undefined') {
this.rstb.show();
if (this.options.controlTime)
this.showcontrolTime();
}
},
hide: function () {
this.options.hidden = true;
if (typeof this.rstb != 'undefined') {
this.rstb.hide();
this.ctp.hide();
}
},
showPanel: function () {
this.options.panel = true;
if (typeof this.tp != 'undefined')
videojs.removeClass(this.tp.el_, 'disable');
},
hidePanel: function () {
this.options.panel = false;
if (typeof this.tp != 'undefined')
videojs.addClass(this.tp.el_, 'disable');
},
showcontrolTime: function () {
this.options.controlTime = true;
if (typeof this.ctp != 'undefined')
this.ctp.show();
},
hidecontrolTime: function () {
this.options.controlTime = false;
if (typeof this.ctp != 'undefined')
this.ctp.hide();
},
setValue: function (index, seconds, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
var percent = this._percent(seconds);
var isValidIndex = (index === 0 || index === 1);
var isChangeable = !this.locked;
if (isChangeable && isValidIndex)
this.box.setPosition(index, percent, writeControlTime);
},
setValues: function (start, end, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
this._reset();
this._setValuesLocked(start, end, writeControlTime);
},
getValues: function () { //get values in seconds
var values = {}, start, end;
start = this.start || this._getArrowValue(0);
end = this.end || this._getArrowValue(1);
return {start: start, end: end};
},
playBetween: function (start, end, showRS) {
showRS = typeof showRS == 'undefined' ? true : showRS;
this.player.currentTime(start);
this.player.play();
if (showRS) {
this.show();
this._reset();
} else {
this.hide();
}
this._setValuesLocked(start, end);
this.bar.activatePlay(start, end);
},
loop: function (start, end, show) {
var player = this.player;
if (player) {
player.on("pause", videojs.bind(this, function () {
this.looping = false;
}));
show = typeof show === 'undefined' ? true : show;
if (show) {
this.show();
this._reset();
}
else {
this.hide();
}
this._setValuesLocked(start, end);
this.timeStart = start;
this.timeEnd = end;
this.looping = true;
this.player.currentTime(start);
this.player.play();
this.player.on("timeupdate", videojs.bind(this, this.bar.process_loop));
}
},
_getArrowValue: function (index) {
var index = index || 0;
var duration = this.player.duration();
duration = typeof duration == 'undefined' ? 0 : duration;
var percentage = this[index === 0 ? "left" : "right"].el_.style.left.replace("%", "");
if (percentage == "")
percentage = index === 0 ? 0 : 100;
return videojs.round(this._seconds(percentage / 100), this.updatePrecision - 1);
},
_percent: function (seconds) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(1, Math.max(0, seconds / duration));
},
_seconds: function (percent) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(duration, Math.max(0, percent * duration));
},
_reset: function () {
var duration = this.player.duration();
this.tpl.el_.style.left = '0%';
this.tpr.el_.style.left = '100%';
this._setValuesLocked(0, duration);
},
_setValuesLocked: function (start, end, writeControlTime) {
var triggerSliderChange = typeof writeControlTime != 'undefined';
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
if (this.options.locked) {
this.unlock();//It is unlocked to change the bar position. In the end it will return the value.
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
this.lock();
} else {
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
}
// Trigger slider change
if (triggerSliderChange) {
this._triggerSliderChange();
}
},
_checkControlTime: function (index, TextInput, timeOld) {
var h = TextInput[0],
m = TextInput[1],
s = TextInput[2],
newHour = h.value,
newMin = m.value,
newSec = s.value,
obj, objNew, objOld;
index = index || 0;
if (newHour != timeOld[0]) {
obj = h;
objNew = newHour;
objOld = timeOld[0];
} else if (newMin != timeOld[1]) {
obj = m;
objNew = newMin;
objOld = timeOld[1];
} else if (newSec != timeOld[2]) {
obj = s;
objNew = newSec;
objOld = timeOld[2];
} else {
return false;
}
var duration = this.player.duration() || 0,
durationSel;
var intRegex = /^\d+$/;//check if the objNew is an integer
if (!intRegex.test(objNew) || objNew > 60) {
objNew = objNew == "" ? "" : objOld;
}
newHour = newHour == "" ? 0 : newHour;
newMin = newMin == "" ? 0 : newMin;
newSec = newSec == "" ? 0 : newSec;
durationSel = videojs.TextTrack.prototype.parseCueTime(newHour + ":" + newMin + ":" + newSec);
if (durationSel > duration) {
obj.value = objOld;
obj.style.border = "1px solid red";
} else {
obj.value = objNew;
h.style.border = m.style.border = s.style.border = "1px solid transparent";
this.setValue(index, durationSel, false);
// Trigger slider change
this._triggerSliderChange();
}
if (index === 1) {
var oldTimeLeft = this.ctpl.el_.children,
durationSelLeft = videojs.TextTrack.prototype.parseCueTime(oldTimeLeft[0].value + ":" + oldTimeLeft[1].value + ":" + oldTimeLeft[2].value);
if (durationSel < durationSelLeft) {
obj.style.border = "1px solid red";
}
} else {
var oldTimeRight = this.ctpr.el_.children,
durationSelRight = videojs.TextTrack.prototype.parseCueTime(oldTimeRight[0].value + ":" + oldTimeRight[1].value + ":" + oldTimeRight[2].value);
if (durationSel > durationSelRight) {
obj.style.border = "1px solid red";
}
}
},
_triggerSliderChange: function () {
this.player.trigger("sliderchange");
}
};
//----------------Public Functions----------------//
//-- Public Functions added to video-js
//Lock the Slider bar and it will not be possible to change the arrow positions
videojs.Player.prototype.lockSlider = function () {
return this.rangeslider.lock();
};
//Unlock the Slider bar and it will be possible to change the arrow positions
videojs.Player.prototype.unlockSlider = function () {
return this.rangeslider.unlock();
};
//Show the Slider Bar Component
videojs.Player.prototype.showSlider = function () {
return this.rangeslider.show();
};
//Hide the Slider Bar Component
videojs.Player.prototype.hideSlider = function () {
return this.rangeslider.hide();
};
//Show the Panel with the seconds of the selection
videojs.Player.prototype.showSliderPanel = function () {
return this.rangeslider.showPanel();
};
//Hide the Panel with the seconds of the selection
videojs.Player.prototype.hideSliderPanel = function () {
return this.rangeslider.hidePanel();
};
//Show the control Time to edit the position of the arrows
videojs.Player.prototype.showControlTime = function () {
return this.rangeslider.showcontrolTime();
};
//Hide the control Time to edit the position of the arrows
videojs.Player.prototype.hideControlTime = function () {
return this.rangeslider.hidecontrolTime();
};
//Set a Value in second for both arrows
videojs.Player.prototype.setValueSlider = function (start, end) {
return this.rangeslider.setValues(start, end);
};
//The video will be played in a selected section
videojs.Player.prototype.playBetween = function (start, end) {
return this.rangeslider.playBetween(start, end);
};
//The video will loop between to values
videojs.Player.prototype.loopBetween = function (start, end) {
return this.rangeslider.loop(start, end);
};
//Set a Value in second for the arrows
videojs.Player.prototype.getValueSlider = function () {
return this.rangeslider.getValues();
};
//----------------Create new Components----------------//
//--Charge the new Component into videojs
videojs.SeekBar.prototype.options_.children.RSTimeBar = {}; //Range Slider Time Bar
videojs.ControlBar.prototype.options_.children.ControlTimePanel = {}; //Panel with the time of the range slider
//-- Design the new components
/**
* Range Slider Time Bar
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
})();
This plugin is not compatible with videojs version over 4.2.
You can look issue here
AND Owner of plugin wroten to github that at the begining of readme "This plugin will no longer be maintained. Welcome those who want to continue the project."
I know very little about Javascript but need to use hammer.js in a project I'm working on.
Instead of replacing/refreshing the image im trying to use the pull to refresh scrit to refresh the page.
Ive tried adding
location.reload();
to the script but to no avail, can anyone shed any light on this.
http://eightmedia.github.io/hammer.js/
This is the code im using
/**
* requestAnimationFrame and cancel polyfill
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
/**
* pull to refresh
* #type {*}
*/
var PullToRefresh = (function() {
function Main(container, slidebox, slidebox_icon, handler) {
var self = this;
this.breakpoint = 80;
this.container = container;
this.slidebox = slidebox;
this.slidebox_icon = slidebox_icon;
this.handler = handler;
this._slidedown_height = 0;
this._anim = null;
this._dragged_down = false;
this.hammertime = Hammer(this.container)
.on("touch dragdown release", function(ev) {
self.handleHammer(ev);
});
};
/**
* Handle HammerJS callback
* #param ev
*/
Main.prototype.handleHammer = function(ev) {
var self = this;
switch(ev.type) {
// reset element on start
case 'touch':
this.hide();
break;
// on release we check how far we dragged
case 'release':
if(!this._dragged_down) {
return;
}
// cancel animation
cancelAnimationFrame(this._anim);
// over the breakpoint, trigger the callback
if(ev.gesture.deltaY >= this.breakpoint) {
container_el.className = 'pullrefresh-loading';
pullrefresh_icon_el.className = 'icon loading';
this.setHeight(60);
this.handler.call(this);
}
// just hide it
else {
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.hide();
}
break;
// when we dragdown
case 'dragdown':
this._dragged_down = true;
// if we are not at the top move down
var scrollY = window.scrollY;
if(scrollY > 5) {
return;
} else if(scrollY !== 0) {
window.scrollTo(0,0);
}
// no requestAnimationFrame instance is running, start one
if(!this._anim) {
this.updateHeight();
}
// stop browser scrolling
ev.gesture.preventDefault();
// update slidedown height
// it will be updated when requestAnimationFrame is called
this._slidedown_height = ev.gesture.deltaY * 0.4;
break;
}
};
/**
* when we set the height, we just change the container y
* #param {Number} height
*/
Main.prototype.setHeight = function(height) {
if(Modernizr.csstransforms3d) {
this.container.style.transform = 'translate3d(0,'+height+'px,0) ';
this.container.style.oTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.msTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.mozTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.webkitTransform = 'translate3d(0,'+height+'px,0) scale3d(1,1,1)';
}
else if(Modernizr.csstransforms) {
this.container.style.transform = 'translate(0,'+height+'px) ';
this.container.style.oTransform = 'translate(0,'+height+'px)';
this.container.style.msTransform = 'translate(0,'+height+'px)';
this.container.style.mozTransform = 'translate(0,'+height+'px)';
this.container.style.webkitTransform = 'translate(0,'+height+'px)';
}
else {
this.container.style.top = height+"px";
}
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.hide = function() {
container_el.className = '';
this._slidedown_height = 0;
this.setHeight(0);
cancelAnimationFrame(this._anim);
this._anim = null;
this._dragged_down = false;
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.slideUp = function() {
var self = this;
cancelAnimationFrame(this._anim);
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.setHeight(0);
setTimeout(function() {
self.hide();
}, 500);
};
/**
* update the height of the slidedown message
*/
Main.prototype.updateHeight = function() {
var self = this;
this.setHeight(this._slidedown_height);
if(this._slidedown_height >= this.breakpoint){
this.slidebox.className = 'breakpoint';
this.slidebox_icon.className = 'icon arrow arrow-up';
}
else {
this.slidebox.className = '';
this.slidebox_icon.className = 'icon arrow';
}
this._anim = requestAnimationFrame(function() {
self.updateHeight();
});
};
return Main;
})();
function getEl(id) {
return document.getElementById(id);
}
var container_el = getEl('container');
var pullrefresh_el = getEl('pullrefresh');
var pullrefresh_icon_el = getEl('pullrefresh-icon');
var image_el = getEl('random-image');
var refresh = new PullToRefresh(container_el, pullrefresh_el, pullrefresh_icon_el);
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
var preload = new Image();
preload.onload = function() {
image_el.src = this.src;
self.slideUp();
};
preload.src = 'http://lorempixel.com/800/600/?'+ (new Date().getTime());
}, 1000);
};
There is a Beer involved for anyone that can fix this :)
http://jsfiddle.net/zegermens/PDcr9/1/
You're assigning the return value of the location.reload function to the src attribute of an Image element. I'm not sure if the function even has a return value, https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Try this:
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
window.location.reload();
}, 1000);
};
I'm facing weird behaviour of Jit Infovis i'm using. I have two different html files that include a load json function from a Javascript file. The function is using infovis library to display a hypertree map from a json file. Both two html files load the same json file.
One html file has been succeeded rendering the map properly. But another one has not. It renders the map almost properly, but after i debugged it, i got it not iterating over the root node. Then, the root node becames inactive without label and clickability.
This is the js function i'm using.
var labelType, useGradients, nativeTextSupport, animate;
(function () {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function (text) {
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (350 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(slugParam, pageParam) {
var isFirst = true;
var isSetAsRoot = false;
// alert(slugParam+ " | "+pageParam);
var url = Routing.generate('trade_map_buyer_json', { slug : slugParam, page : pageParam });
//init data
$.getJSON(url, function (json) {
var type = 'Buyer';
//end
var infovis = document.getElementById('infovis');
infovis.style.align = "center";
infovis.innerHTML = '';
// infovis.innerHTML = '<img align="center" id="gifloader" style="margin-left:50%; margin-top:50%" src="{{ asset('/bundles/jariffproject/frontend/images/preloader.gif') }}" width="30px" height="30px"/>'
var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
url = url.replace("/json/", "/");
window.history.pushState("object or string", "Title", url);
//init Hypertree
var ht = new $jit.Hypertree({
//id of the visualization container
injectInto: 'infovis',
Navigation: {
enable: false,
panning: 'avoid nodes',
},
//canvas width and height
width: w,
height
: h,
//Change node and edge styles such as
//color, width and dimensions.
Node: {
dim: 9,
overridable: true,
color: "#66FF33"
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 0,
offsetY: 0,
onShow: function(tip, node) {
// dump(tip);
tip.innerHTML = "<div style='background-color:#F8FFC9;text-align:center;border-radius:5px; padding:10px 10px;' class='node-tip'><p style='font-size:100%;font-weight:bold;'>"+node.name+"</p><p style='font-size:50%pt'>"+node.data.address+"</p></div>";
}
},
Events: {
enable: true,
type: 'HTML',
onMouseEnter: function(node, eventInfo, e){
var nodeId = node.id;
var menu1 = [
{'set as Root':function(menuItem,menu) {
menu.hide();
isSetAsRoot = true;
console.log(nodeId);
init(nodeId, 0);
}},
$.contextMenu.separator,
{'View details':function(menuItem,menu) {
}}
];
$('.node').contextMenu(menu1,{theme:'vista'});
}
},
Edge: {
lineWidth: 1,
color: "#52D5DE",
overridable: true,
},
onBeforePlotNode: function(node)
{
if (isFirst) {
console.log(node._depth);
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
isFirst = false;
}
},
onPlotNode: function(node)
{
if (isSetAsRoot) {
var nodeInstance = node.getNode();
var nodeId = nodeInstance.id;
init(nodeId, 0);
isSetAsRoot = false;
}
},
onBeforeCompute: function (domElement, node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
type = isOdd(dot._depth) ? 'Supplier' : 'Buyer';
},
//Attach event handlers and add text to the
//labels. This method is only triggered on label
//creation
onCreateLabel: function (domElement, node) {
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
domElement.innerHTML = node.name;
// if (node._depth == 1) {
console.log("|"+node.name+"|"+node._depth+"|");
// }
$jit.util.addEvent(domElement, 'click', function () {
ht.onClick(node.id, {
onComplete: function () {
console.log(node.id);
ht.controller.onComplete(node);
}
});
});
},
onPlaceLabel: function (domElement, node) {
var style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#000";
style.fontWeight = "normal";
} else if (node._depth == 2) {
style.fontSize = "0.7em";
style.color = "#555";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onComplete: function (node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
console.log(dot._depth);
var connCount = dot.data.size;
var showingCount = '';
if (connCount != undefined) {
var pageParamInt = (parseInt(pageParam)+1) * 10;
var modulus = connCount%10;
showingCount = (pageParamInt - 9) + " - " + pageParamInt;
if (connCount - (pageParamInt - 9) < 10) {
showingCount = (pageParamInt - 10) + " - " + ((pageParamInt - 10) + modulus);
}
} else {
connCount = '0';
showingCount = 'No Connections Shown'
}
}
});
//load JSON data.
ht.loadJSON(json);
//compute positions and plot.
ht.refresh();
//end
ht.controller.onComplete();
});
}
function isEven(n)
{
return isNumber(n) && (n % 2 == 0);
}
function isOdd(n)
{
return isNumber(n) && (n % 2 == 1);
}
function isNumber(n)
{
return n === parseFloat(n);
}
function processAjaxData(response, urlPath){
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
out = out + "\n\n"
console.log(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
What's probably causing this?
Please check whether there is conflict id. Basically infovis render each nodes by the id.
And if there is an DOM element that has the same id with one DOM element of a node. It would conflict and won't render
you can check it by duming dom element iterating over the nodes.
I can't find where i can put my own code on resize and reposition. I need to find where to insert the callback, this is the only bit i should be looking at and i just can't find where to insert the callback function on resize
$.Isotope.prototype._getCenteredMasonryColumns = function() {
this.width = this.element.width();
var parentWidth = this.element.parent().width();
// i.e. options.masonry && options.masonry.columnWidth
var colW = this.options.masonry && this.options.masonry.columnWidth ||
// or use the size of the first item
this.$filteredAtoms.outerWidth(true) ||
// if there's no items, use size of container
parentWidth;
var cols = Math.floor( parentWidth / colW );
cols = Math.max( cols, 1 );
// i.e. this.masonry.cols = ....
this.masonry.cols = cols;
// i.e. this.masonry.columnWidth = ...
this.masonry.columnWidth = colW;
};
$.Isotope.prototype._masonryReset = function() {
// layout-specific props
this.masonry = {};
// FIXME shouldn't have to call this again
this._getCenteredMasonryColumns();
var i = this.masonry.cols;
this.masonry.colYs = [];
while (i--) {
this.masonry.colYs.push( 0 );
}
};
$.Isotope.prototype._masonryResizeChanged = function() {
var prevColCount = this.masonry.cols;
// get updated colCount
this._getCenteredMasonryColumns();
return ( this.masonry.cols !== prevColCount );
};
$.Isotope.prototype._masonryGetContainerSize = function() {
var unusedCols = 0,
i = this.masonry.cols;
// count unused columns
while ( --i ) {
if ( this.masonry.colYs[i] !== 0 ) {
break;
}
unusedCols++;
}
return {
height : Math.max.apply( Math, this.masonry.colYs ),
// fit container to columns that have been used;
width : (this.masonry.cols - unusedCols) * this.masonry.columnWidth
}
};
Any idea?
Solution was to simply do a window.resize an apply a timer in it:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function() {
delay(function(){
if ($("#head").width() != $("#container").width()){
var myLeft = $("#container").offset().left;
var newWidth = $("#container").innerWidth();
var myRight = $("#container").offset().left + $("#container").outerWidth();
$("#head").animate({ width: newWidth, marginLeft: myLeft, marginRight: myRight }, "fast");
}
}, 800);
});