Define ImageSize in div dwtcontrolContainer Dynamic Web TWAIN SDK APIs - javascript

How can I adjust the size of scanned image in dwtcontrolContainer div? Because when I scroll down the screen, the selected area never follows the mouse and select an area above the mouse click.
Bellow is my AcquireImage function:
function AcquireImage() {
try {
if (DWObject) {
var _obj = {};
_obj.IfShowUI = false;
_obj.PixelType = 0;
_obj.Resolution = 300;
_obj.IfFeederEnabled = true;
_obj.IfDuplexEnabled = false;
_obj.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan.
_obj.Brightness = 10000;
_obj.MaxImagesInBuffer = 3;
_obj.PageSize = 0;
_obj.Contrast = 1000;
DWObject.SelectSourceByIndex(document.getElementById("rdlScanner").selectedIndex);
DWObject.OpenSource();
DWObject.AcquireImage(_obj);
DWObject.SetViewMode(-1, -1);
DWObject.CurrentImageIndexInBuffer = 0;
updatePageInfo();
}
}
catch (err) {
alert("Error: " + err.message);
}
}
I found http://developer.dynamsoft.com/dwt/dynamic-web-twain-how-to-resize-the-viewer-automatically but even configure the .js dynamsoft.webtwain.config.js doesn't work

Your link is about how to change the size of the viewer, not the image size. Here I changed your viewer size to 600x800:
function AcquireImage() {
try {
if (DWObject) {
DWObject.Width = 600; // viewer width
DWObject.Height = 800; // viewer height
var _obj = {};
_obj.IfShowUI = false;
_obj.PixelType = 0;
_obj.Resolution = 300;
_obj.IfFeederEnabled = true;
_obj.IfDuplexEnabled = false;
_obj.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan.
_obj.Brightness = 10000;
_obj.MaxImagesInBuffer = 3;
_obj.PageSize = 0;
_obj.Contrast = 1000;
DWObject.SelectSourceByIndex(document.getElementById("rdlScanner").selectedIndex);
DWObject.OpenSource();
DWObject.AcquireImage(_obj);
DWObject.SetViewMode(-1, -1);
DWObject.CurrentImageIndexInBuffer = 0;
updatePageInfo();
}
}
catch (err) {
alert("Error: " + err.message);
}
}
If you want to change the image size, visit this link: http://developer.dynamsoft.com/dwt/changeimagesize.
I created two buttons to change the image size:
function small() {
var DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
DWObject.ChangeImageSize(0, 300, 400, EnumDWT_InterpolationMethod.IM_NEARESTNEIGHBOUR);
}
function big() {
var DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
DWObject.ChangeImageSize(0, 600, 800, EnumDWT_InterpolationMethod.IM_NEARESTNEIGHBOUR);
}

Related

Phaser game getting slow [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Fist time i am using phaser.io, i am repeating background and also loading other thing in update function but after few second later my game is slowing time . it look like background is not moving more. Please have a look of my code and help me in for sort out this problem. Or please give any idea to change background repeatedly without changing other thing.
I have some code indentation problem sorry for that but please try to manage and help me.
Game.js
var scoreTxt, score, speed, scoreTextValue, ques_label, ques_label_pizza, scoreTextKey, timerTextValue, timerTextKey, textStyle_Key, textStyle_Value, anscloud, astroid1, astroid2, astroid3, astroid4;
/*var gameType;*/ //Pizza or Noun
var bullets, quesTextValue, ansTextValue, sprite;
var fireRate = 100;
var nextFire = 0;
var xAxis = [];
var yAxis = [];
var tempQues = [];
var tempAns = [];
var result = [];
var answear = [];
var ques = [];
var astroidContains = [];
var astroidContainsText = []; //['right', 'wrong', 'wrong', 'wrong']
var astroid, spaceShip, quesbar, diamond, randomAnsPosition;
var s1Copy;
var cloudContains = []; //['noun', 'pronoun', 'pronoun']
var QbarContainsQue = [];
var ans,rightans;
var isAnswerCorrect = false;
var allowClick = false;
var spaceShipXAxis = 40, loader1Width = 85, loader2Width = 70;
var bar, loader1, loader2, timer, timerSprite, timerSpriteCount = 0;
var timerCounter = 45; //timer counter will be of 45 seconds.
//var timerCounter_ = 100; //timer counter will be of 45 seconds.
var questCounter = 0; //question counter no. of question played.
var maxQuest = 10;//max questions will be displayed is 10.
var diamondTextColor = "#8D4FA8";
var defTextColor = "#5BEFFE";
var ansTextColor = "#9E13DA";
var errTextColor = '#FF0000';
var corrTextColor = '#228B22';
var corr_ans_fst;
var corr_ans_sec;
var fun_bckg, randQues;
var wrong_ans;
var barre1_x = 150;
var barre1_y = 115;
var healthValue = 100;
var x_loader = 180;
var check =0;
var setAns = [];
var setOne = [['12+16=','28'], ['15+11=','26'], ['16+22=','38'], ['13+14=','27'], ['15+24=','39'], ['14+12=','26'], ['10+17=','27'], ['11+11=','22'],
['13+15=','28'], ['12+21=','33'], ['24+13=','37'], ['33+21=','54'], ['40+18=','58'], ['34+31=','65'], ['25+42=','67'], ['22+15=','37'],
['24+12=','36'], ['20+15=','35'], ['25+14=','39'], ['21+21=','42'], ['41+25=','66'], ['53+24=','77'], ['35+31=','66'], ['62+37=','99'],
['54+35=','89']];
var setTwo = [['15+18=','33'], ['17+17=','34'], ['13+19=','32'], ['18+14=','32'], ['15+27=','42'], ['18+17=','35'], ['27+29=','56'], ['23+28=','51'],
['36+37=','73'], ['45+25=','70'], ['46+45=','91'], ['38+57=','95'], ['49+43=','92'], ['37+53=','90'], ['48+33=','81']];
var Game = {
preload : function() {
// Load the needed image for this(play) game screen.
//load the menu screen
this.load.image('menu', './assets/images/menu.png');
// Here we load all the needed resources for the level.
// background image screen
this.load.image('playgame', './assets/images/back.png');
// globe image screen
this.load.image('playgame', './assets/images/back.png');
// win image screen
//this.load.image('win', './assets/images/win.png');
// spaceship image screen
this.load.image('spaceship', './assets/images/spaceship.png');
// Question bar image screen
this.load.image('quesbar', './assets/images/quesbar.png');
// Diamond image screen
this.load.image('diamond', './assets/images/diamond.png');
// Astroid image screen
this.load.image('astroid1', 'assets/images/asteroid1.png');
this.load.image('astroid2', 'assets/images/asteroid2.png');
this.load.image('astroid3', 'assets/images/asteroid3.png');
this.load.image('astroid4', 'assets/images/asteroid4.png');
// Loader image screen
this.load.image('loaderbck', 'assets/images/loaderbck.png');
this.load.image('loader1', 'assets/images/loader1.png');
this.load.image('loader2', 'assets/images/loader2.png');
//Load the bullet
this.load.image('bullet', 'assets/images/bullet.png');
},
create : function() {
// By setting up global variables in the create function, we initialise them on game start.
// We need them to be globally available so that the update function can alter them.
textStyle_Value = { font: "bold 20px Segoe UI", fill: defTextColor, align: "center" };
textStyleAns = { font: "bold 22px 'Comic Sans MS', 'Comic Sans'", fill: ansTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
textStyleQues = { font: "bold 20px 'Comic Sans MS', 'Comic Sans'", fill: defTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
sprite = game.add.sprite(310, 485, 'spaceship');
sprite.anchor.set(0.5);
// Loading backround image
this.playBackground();
this.playBackground1();
// Additional Sprites, like cloud
this.addSprites();
// Loading spaceship image
//this.spaceship();
// Loading questionbar image
this.questionbar();
// Call fun. for ques
this.comeQus();
// csll fun. for place astroid
// this.astroid();
// call fun. for Ans
this.generateQues();
this.generateAns();
// Loading Diamond image
this.diamond();
// Start timer
this.startTimer();
// Set timer.
this.setTimer();
this.initLoader();
},
update: function() {
// The update function is called constantly at a high rate (somewhere around 60fps),
// updating the game field every time - also destroying previous objects and creating new.
// Our bullet group
//bullets.destroy();
sprite.destroy();
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
//Repeating background..
if(playgame != null && playgame.body.y > 600) {
playgame.destroy();
this.playBackground();
}
if(playgame1.body.y > 0) {
playgame1.destroy();
this.playBackground1();
this.initLoader();
}
if(astroid1 != undefined) astroid1.destroy();
if(astroid2 != undefined) astroid2.destroy();
if(astroid3 != undefined) astroid3.destroy();
if(astroid4 != undefined) astroid4.destroy();
this.addSprites();
//timerTextValue.text = "00:" + timerCounter;
this.initLoader();
//destroing old diamond obj and creating new while change background
//diamond.destroy();
this.diamond();
//destroing old questionbar obj and creating new while change background
quesbar.destroy();
this.questionbar();
//Call comeQus, comeAns for show ques and ans at every background change
// quesTextValue.destroy();
if(quesTextValue != undefined) quesTextValue.destroy();
this.comeQus();
//ansTextValue.destroy();
if(ansTextValue != undefined) ansTextValue.destroy();
this.comeAns();
if (game.input.activePointer.isDown) {
this.fire();
}
allowClick = true;
},
playBackground: function() {
// console.log("playBackground called");
playgame = this.add.sprite(0, 0, 'playgame', 5);
playgame.scale.set(1);
playgame.smoothed = false;
anim_playgame = playgame.animations.add('walk');
anim_playgame.play(10, true);
this.physics.enable(playgame, Phaser.Physics.ARCADE);
playgame.body.velocity.y = 50;
},
playBackground1: function() {
//console.log("playBackground1 called");
//Second background..
playgame1 = this.add.sprite(0, -600, 'playgame', 5);
playgame1.scale.set(1);
playgame1.smoothed = false;
anim_playgame1 = playgame1.animations.add('walk');
anim_playgame1.play(10, true);
this.physics.enable(playgame1, Phaser.Physics.ARCADE);
playgame1.body.velocity.y = 50;
},
questionbar: function() {
quesbar = game.add.image(10, 530, 'quesbar');
},
diamond: function() {
diamond = game.add.image(680, 20, 'diamond');
},
addSprites: function() {
// loading answer cloud
astroid1 = this.add.button(30, 90, 'astroid1', this.astroidClicked, this);
astroid2 = this.add.button(220, 30, 'astroid2', this.astroidClicked, this);
astroid3 = this.add.button(400, 40, 'astroid3', this.astroidClicked, this);
astroid4 = this.add.button(600, 90, 'astroid4', this.astroidClicked, this);
},
inCorrectAnswerHit: function(index) {
allowClick = false;
isAnswerCorrect = false;
//this.playFx('wrong_ans');
for(i=0; i<=3; i++) {
if(cloudContains[i] == "right") {
//cloudContainsText[i].fill = corrTextColor;
console.log("right ans hit");
break;
}
}
},
checkAnswer: function(index) {
// If clicked Ans is right so astroid will destroy.
if(astroidContainsText[index] == "wrong") {
//Here collization function will call
isAnswerCorrect = true;
}
// If clicked word is noun (correct answer) and obstacle is redbird or blackbird - the dude will slide.
else {
this.inCorrectAnswerHit(index);
}
},
generateQues: function(){
var que;
// Generating random questions from given list of ques - setOne.
s1Copy = setOne.slice();
//var result = [];
for (var i = 0; i < 3; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
s1Copy.push(...setTwo);
for (var i = 0; i < 7; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
result.toString();
for(var i = 0; i < result.length ; i++ ) {
que = result[i];
ques.push(que[0]);
ques.toString();
//console.log(ques);
answear.push(que[1]);
}
},
comeQus: function() {
quesTextValue = this.add.text(50,541, ques[0],textStyleQues);
this.generateQues();
//tempNoun = [];
},
generateAns: function() {
//Generate two digitd rendom no. and create an array of ans setAns[]
// Add digitd in array
for(var i = 0; i < 3 ; i++) {
var digit = Math.floor(Math.random() * 90 + 10);
//console.log(digit);
setAns.push(digit);
astroidContains[i] = "wrong";
}
console.log(astroidContains);
//console.log(answear);
setAns.push(answear[0]);
astroidContains[i] = "right";
console.log(astroidContains);
shuffle(setAns);
randomAnsPosition = [0, 1, 2, 3];
shuffle(randomAnsPosition);
},
comeAns: function() {
// x and y axis param for placing Answers text.
xAxis = [ 85, 255, 453, 675];
yAxis = [130, 48, 60, 120];
// console.log(setAns);
// Set Answers from above array of Ans - setAns.
for (var i = 0; i < setAns.length; i++) {
var ans = setAns[i];
//console.log(ans);
ansTextValue = this.add.text(xAxis[randomAnsPosition[i]], yAxis[randomAnsPosition[i]], ans, textStyleAns);
astroidContainsText[i] = ansTextValue;
//console.log(ansTextValue.text);
}
},
// Observing which cloud is clicked and checking answer accordingly.
astroidClicked: function() {
// alert("HEllo called");
if(!allowClick) {
return;
}
if(astroid1.game.input._x > 85 && astroid1.game.input._x < 130) {
console.log("cloud_1_Clicked, Clicked:" + astroidContains[0]);
this.checkAnswer(0);
}
else if(astroid2.game.input._x > 255 && astroid2.game.input._x < 48) {
//console.log("cloud_2_Clicked, Clicked:" + astroidContains[1]);
this.checkAnswer(1);
}
else if(astroid3.game.input._x > 453 && astroid3.game.input._x < 60) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(2);
}
else if(astroid4.game.input._x > 675 && astroid4.game.input._x < 120) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(3);
}
allowClick = false;
},
startTimer: function() {
// Create our Timer
timer = game.time.create(false);
// Set a TimerEvent to occur after 1 seconds
timer.loop(1000, this.updateCounter, this);
// Set a TimerEvent to occur after 1 seconds
// timer.loop(100, this.timerStripeChange, this);
// Start the timer running - this is important!
// It won't start automatically, allowing you to hook it to button events and the like.
timer.start();
},
gameOver: function() {
//Gameover screen
this.state.start('Game_Over', true, false);
},
initLoader: function() {
//*******Loader
check +=1;
var bmd = this.game.add.bitmapData(185, 30);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 185, 36);
bmd.ctx.fillStyle = '#00685e';
bmd.ctx.fill();
var bglife = this.game.add.sprite(100, 38, bmd);
bglife.anchor.set(0.5);
if(check != 0)
bmd = this.game.add.bitmapData(x_loader-4, 26);
else
bmd = this.game.add.bitmapData(x_loader, 26);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 180, 26);
if(x_loader <= 120 && x_loader > 60) {
bmd.ctx.fillStyle = "#FFFF00";
} else if(x_loader <= 60) {
bmd.ctx.fillStyle = "#EA0B1E";
} else {
bmd.ctx.fillStyle = '#00f910';
}
bmd.ctx.fill();
this.widthLife = new Phaser.Rectangle(0, 0, bmd.width, bmd.height);
this.totalLife = bmd.width;
//x_loader = ;
/*console.log(this.totalLife);
console.log(this.widthLife);*/
this.life = this.game.add.sprite(93 - bglife.width/2 + 10, 38, bmd);
this.life.anchor.y = 0.5;
this.life.cropEnabled = true;
this.life.crop(this.widthLife);
// this.game.time.events.loop(1450, this.cropLife, this);
},
updateCounter: function() {
if(timerCounter <= 0) {
this.gameOver();
return;
}
timerCounter--;
if(this.widthLife.width <= 0){
this.widthLife.width = this.totalLife;
}
else{
//this.game.add.tween(this.widthLife).to( { width: (x_loader - 4) }, 200, Phaser.Easing.Linear.None, true);
//console.log(this.widthLife.width);
this.widthLife.width = x_loader - 4;
x_loader = this.widthLife.width;
}
},
fire: function () {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 80, sprite.y - 80);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
}
/**
* Shuffles array in place.
* #param {Array} a items The array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
As already noted it is a lot of code.
So far what I can see, is a memory leak in the update() function:
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
With that you are constantly creating new bullets. Put that in the create() function and try again.

Using PreloadJS to load images and adding them to CreateJS stage

I'm trying to create a Tri Peaks Solitaire game in Javascript, using CreateJS to help interact with the HTML canvas. I'm not entirely new to programming, as I've taken college courses on Java and C, but I am new to both Javascript and HTML.
I created a large amount of the card game using a Card class and Deck class, with the image adding, event listening, and game logic done in one Javascript file, but this resulted in a lot of messy, somewhat buggy code that I felt needed cleaning up.
I'm trying to implement a separate class for the card table, which will be the canvas, or stage, and it will draw the 4 rows of playable cards, the stock pile, and the waste pile. I'm currently just trying to get the stock pile to show up on the canvas, but it's not happening.
My question is, why is my stock pile not showing up? Also, as you can see, the card images are being loaded when the cards are created. Should I be doing that differently?
Card class:
var Card = function(number) {
this.isFaceUp = false;
//number for image file path
this.number = number;
this.value = Math.ceil( (this.number)/4 );
//back of the card is default image
this.initialize("images/" + 0 + ".png");
console.log("card created")
this.height = this.getBounds().height;
this.width = this.getBounds().width;
//load the card's front image
this.frontImage = new Image();
this.frontImage.src = ( this.getImagePath() );
};
Card.prototype = new createjs.Bitmap("images/" + this.number + ".png");
Card.prototype.getImagePath = function() {
return "images/" + this.number + ".png";
};
Card.prototype.getValue = function () {
return this.value;
}
Card.prototype.flip = function() {
// this.image = new Image();
// this.image.src = ( this.getImagePath() );
this.image = this.frontImage;
this.isFaceUp = true;
};
Card.prototype.getHeight = function() {
return this.height;
};
Card.prototype.getWidth = function() {
return this.width;
};
CardDeck class:
function CardDeck() {
//create empty array
this.deck = [];
//fill empty array
for(i=1; i<=52; i++) {
//fill deck with cards, with i being the number of the card
this.deck[i-1] = new Card(i);
}
//shuffle deck
this.shuffle();
}
CardDeck.prototype.getCard = function() {
if(this.deck.length < 1) alert("No cards in the deck");
return this.deck.pop();
};
CardDeck.prototype.getSize = function() {
return this.deck.length;
};
CardDeck.prototype.shuffle = function() {
for (i=0; i<this.deck.length; i++) {
var randomIndex = Math.floor( Math.random()*this.deck.length );
var temp = this.deck[i];
this.deck[i] = this.deck[randomIndex];
this.deck[randomIndex] = temp;
}
};
CardDeck.prototype.getRemainingCards = function() {
return this.deck.splice(0);
}
CardDeck.prototype.listCards = function() {
for(i=0; i<this.deck.length; i++) {
console.log(this.deck[i].number);
}
};
CardTable class:
var CardTable = function(canvas) {
this.initialize(canvas);
this.firstRow = [];
this.secondRow = [];
this.thirdRow = [];
this.fourthRow = [];
this.stockPile = [];
this.wastePile = [];
//startX is card width
this.startX = ( new Card(0) ).width*3;
//startY is half the card height
this.startY = ( new Card(0) ).height/2;
};
CardTable.prototype = new createjs.Stage();
CardTable.prototype.createStockPile = function(cards) {
for(i=0; i<23; i++) {
cards[i].x = 10;
cards[i].y = 50;
this.stockPile[i] = cards[i];
}
};
CardTable.prototype.addToWastePile = function(card) {
card.x = startX + card.width;
card.y = startY;
this.wastePile.push(card);
this.addChild(card);
this.update();
};
CardTable.prototype.drawStockPile = function() {
for(i=0; i<this.stockPile.length; i++) {
console.log("this.stockPile[i]");
this.addChild(this.stockPile[i]);
}
this.update();
};
HTML file:
<html>
<head>
<title>Tri-Peaks Solitaire</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
<script src="card.js"></script>
<script src="carddeck.js"></script>
<script src="cardtable.js"></script>
<script>
function init(){
var canvas = document.getElementById("canvas");
var table = new CardTable("canvas");
deck = new CardDeck();
table.createStockPile(deck.getRemainingCards());
table.drawStockPile();
table.update();
}
</script>
</head>
<body onload="init()">
<h1>Tri-Peaks Solitaire</h1>
<canvas style='border: 5px solid green; background: url("images/background.jpg");'
id="canvas" width="1000" height="450">
</canvas>
</body>
</html>
PRELOADJS UPDATE:
var canvas = document.getElementById("canvas");
var stage = new createjs.Stage(canvas);
var gameDeck = new CardDeck();
var numbers = [];
var preloader;
var progressText = new createjs.Text("", "20px Arial","#FF0000");
progressText.x = 50;
progressText.y = 20;
stage.addChild(progressText);
stage.update();
setupManifest();
startPreload();
function setupManifest() {
for(i=0; i<=52; i++) {
console.log("manifest");
manifest.push( {src:"images/" + i + ".png",
id: i} );
numbers.push(i);
}
}
function startPreload() {
preload = new createjs.LoadQueue(true);
preload.on("fileload", handleFileLoad);
preload.on("progress", handleFileProgress);
preload.on("complete", loadComplete);
preload.on("error", loadError);
preload.loadManifest(manifest);
}
function handleFileLoad(event) {
console.log("A file has loaded of type: " + event.item.type);
//console.log(numbers.pop());
var cardNumber = numbers.pop();
var newCard = new Card(cardNumber);
//faces.push( new Image() );
//faces[ faces.length - 1 ].src = "images/" + cardNumber + ".png";
gameDeck.insertCard(newCard);
}
function loadError(evt) {
console.log("error",evt.text);
}
function handleFileProgress(event) {
progressText.text = (preload.progress*100|0) + " % Loaded";
stage.update();
}
function loadComplete(event) {
console.log("Finished Loading Assets");
}
You are only updating the stage immediately after creating the cards. The cards are loading bitmap images, which is a concurrent operation that takes time. As such, the only time you render the stage is before the images load.
I would suggest using PreloadJS to preload your card images. This will also give you a lot more control over when / how they load, and let you show a progress bar or distractor to the user as they load.
I would suggest waiting for all the images to load and then calling stage.update(). Alternatively use the createjs.Ticker.addEventListener("tick", handleTick); event handler to update the stage for you.
Reference: http://www.createjs.com/docs/easeljs/classes/Ticker.html

HTML5 & javascript - drawImage seems to trigger after animation completed

I'm trying to create the following animation:
- when the page loads, I load the 2 components of my logo and draw them onto the canvas
- after clicking the animate button, both images should smoothly move up to the top of the page and shrink
However, it seems that the drawImage() only takes place somewhere after the entire animation has been completed even though I can see it being executed at the right time in the console. Commenting out the clearRect function also shows me that every frame is actually drawn onto the screen, but sadly they all appear together after the animation should be completed.
I'm pretty new to canvases and relevant tutorials on such animations are scarce and don't get me much further.
Here's the relevant script:
<script type="text/javascript">
var logoCanvas;
var logoContext;
var direction = 1;
var logoAnimationDuration = 2000; //millisec
var frameSpeed = 30/1000; //frames per second
var logoImageRatio = 0;
var logoTextRatio = 0;
var initialLogoImageHeight = 0;
var initialLogoTextHeight = 0;
var initialLogoImageTop = 0;
var initialLogoImageLeft = 0;
var initialLogoTextTop = 0;
var initialLogoTextLeft = 0;
var newLogoImageLeft = 0;
var logoImageWidth = 0;
var logoImageHeight = 0;
var logoTextWidth = 0;
var logoTextHeight = 0;
var logoImageTop = 0;
var logoImageLeft = 0;
var logoTextTop = 0;
var logoTextLeft = 0;
var logoImageLoaded = false;
var logoTextLoaded = false;
var logoImage = new Image();
var logoText = new Image();
function AnimateFrontPageCanvas() {
if(logoCanvas.height <= $('#Page_0').height()) {
logoCanvas.height = $('#Page_0').height();
return;
}
if(logoImageHeight <= $('#Page_0').height() - 4) {
return;
}
if(logoImageTop <= 2) {
return;
}
//logoCanvas.height = parseFloat(logoCanvas.height) - (parseFloat(window.innerHeight) - parseFloat($('#Page_0').height())) * 1/frameSpeed * 1/logoAnimationDuration;
logoContext.clearRect(0, 0, logoCanvas.width, logoCanvas.height);
AnimateLogo();
setTimeout(AnimateFrontPageCanvas(), 1/frameSpeed);
}
function AnimateLogo() {
AnimateLogoImage();
AnimateLogoText();
}
function AnimateLogoImage() {
logoImageHeight = logoImageHeight - (initialLogoImageHeight - $('#Page_0').height() + 4) * (1/frameSpeed) * (1/logoAnimationDuration);
logoImageWidth = logoImageHeight*logoImageRatio;
logoImageTop = logoImageTop - (initialLogoImageTop - 2)*(1/frameSpeed) * (1/logoAnimationDuration);
logoImageLeft = logoImageLeft - (initialLogoImageLeft - newLogoImageLeft) * (1/frameSpeed) * (1/logoAnimationDuration);
logoContext.drawImage(logoImage, logoImageLeft, logoImageTop, logoImageWidth, logoImageHeight);
var time = new Date();
time = time.getTime();
console.log('logoimage drawn: ' + time);
}
function AnimateLogoText() {
logoTextHeight = logoTextHeight - (initialLogoTextHeight - $('#Page_0').height() + 4) * (1/frameSpeed) * (1/logoAnimationDuration);
logoTextWidth = logoTextHeight*logoTextRatio;
logoTextTop = logoTextTop - (initialLogoTextTop - 2) * (1/frameSpeed)*(1/logoAnimationDuration);
logoTextLeft = logoTextLeft - (initialLogoTextLeft - newLogoTextLeft)*(1/frameSpeed)*(1/logoAnimationDuration);
logoContext.drawImage(logoText, logoTextLeft, logoTextTop, logoTextWidth, logoTextHeight);
var time = new Date();
time = time.getTime();
console.log('logotext drawn: ' + time);
}
function InitiateFrontPageCanvas() {
logoImage.onload = function() {
logoImageLoaded = true;
AfterImagesLoadedActions();
}
logoImage.src = '/site_mats/images/logo_image.png';
logoText.onload = function() {
logoTextLoaded = true;
AfterImagesLoadedActions();
}
logoText.src = '/site_mats/images/logo_text.png';
}
function AfterImagesLoadedActions() {
if(logoImageLoaded && logoTextLoaded) {
logoImageRatio = logoImage.width/logoImage.height;
logoTextRatio = logoText.width/logoText.height;
if(logoImage.width > 0.8*logoCanvas.width) {
logoImage.width = 0.8*logoCanvas.width;
logoImage.height = logoImage.width/logoImageRatio;
}
if(logoText.width > 0.8*logoCanvas.width) {
logoText.width = 0.8*logoCanvas.width;
logoText.height = logoText.width/logoTextRatio;
}
if(parseFloat(logoImage.height) + parseFloat(logoText.height) > 0.66*logoCanvas.height) {
var x = (0.66*logoCanvas.height)/(parseFloat(logoImage.height) + parseFloat(logoText.height));
logoImage.height = x*logoImage.height;
logoImage.width = logoImage.height*logoImageRatio;
logoText.height = x*logoText.height;
logoText.width = logoText.height*logoTextRatio;
}
initialLogoImageHeight = logoImage.height;
initialLogoTextHeight = logoText.height;
logoImageHeight = logoImage.height;
logoImageWidth = logoImage.width;
logoTextHeight = logoText.height;
logoTextWidth = logoText.width;
initialLogoImageTop = parseFloat((logoCanvas.height-(parseFloat(logoImageHeight)+parseFloat(logoTextHeight)))/2);
initialLogoImageLeft = parseFloat((logoCanvas.width-logoImageWidth)/2);
initialLogoTextTop = parseFloat(((logoCanvas.height-(parseFloat(logoImageHeight)+parseFloat(logoTextHeight)))/2)+parseFloat(logoImageHeight));
initialLogoTextLeft = parseFloat((logoCanvas.width-logoImageWidth)/2);
logoImageTop = initialLogoImageTop;
logoImageLeft = initialLogoImageLeft;
logoTextTop = initialLogoTextTop;
logoTextLeft = initialLogoTextLeft;
newLogoImageLeft = parseFloat(2);
newLogoTextLeft = parseFloat((logoCanvas.width-$('#Page_0').height()*logoTextRatio)/2);;
logoContext.drawImage(logoText, logoTextLeft, logoTextTop, logoTextWidth, logoTextHeight);
logoContext.drawImage(logoImage, logoImageLeft, logoImageTop, logoImageWidth, logoImageHeight);
//remove onload from image objects
logoImage.onload = null;
logoText.onload = null;
}
}
function SetFrontPageCanvas() {
logoCanvas = document.getElementById('LogoCanvas');
logoContext = logoCanvas.getContext('2d');
logoCanvas.width = window.innerWidth;
logoCanvas.height = window.innerHeight;
logoContext.clearRect(0, 0, logoCanvas.width, logoCanvas.height);
InitiateFrontPageCanvas();
}
window.onload = function() {
SetFrontPageCanvas();
};
$(document).ready(function() {
windowWidth = $(window).width();
windowHeight = $(window).height();
});
$(window).resize(function() {
//alert($(window).width() + ' - ' + $(window).height());
logoImageLoaded = false;
logoTextLoaded = false;
SetFrontPageCanvas();
windowWidth = $(window).width();
windowHeight = $(window).height();
});
</script>
And here's the relevant html:
<canvas id="LogoCanvas" style="position:absolute;top:0;left:0;z-index:1;"></canvas>
<div id="Page_0" style="position:absolute;top:0;left:0;z-index:5;width:100%;height:90px;">
<div align="center" style="position:fixed;bottom:5px;z-index:100;width:100%;">
<input type="button" onClick="AnimateFrontPageCanvas()" value="Animate">
</div>
If desired, the code can also be seen in action here: http://villa-gloria-katouna.com/site_mats/animation.php

Need help in displaying selection handles on rectangle using javascript

I am trying to add something to my code so as to select the image after drawing ( the selection handler should appear in the corners and in the middle of edge) and then drag or increase/decrease the height and width?
My sample code is in the fiddle , in this I am drawing a rectangle using the mouse event handlers. I want to select the rectangle and modify/alter it using the selection handlers instead of drawing it again.
Click the button ROI, metrics and then you can draw it using the mouse events.
http://jsfiddle.net/AhdJr/53/
var oImageBuffer = document.createElement('img');
var oCanvas=document.getElementById("SetupImageCanvas");
var o2DContext=oCanvas.getContext("2d");
var oRect = {};
var oROI = {};
var oMetrics ={};
var oLayers = new Array();
var bDragging = false;
var bSetROI = false;
var bSetLayers = false;
InitMouseEvents();
var oSelect = document.getElementById("ImageList");
oSelect.onchange=function() {
changeCanvasImage(oSelect[oSelect.selectedIndex].value);
}
// Canvas event handlers (listeners).
function InitMouseEvents() {
oCanvas.addEventListener('mousedown', MouseDownEvent, false);
oCanvas.addEventListener('mouseup', MouseUpEvent, false);
oCanvas.addEventListener('mousemove', MouseMoveEvent, false);
oCanvas.addEventListener('mouseout', MouseOutEvent, false);
}
function MouseDownEvent(e) {
oRect.startX = e.pageX - this.offsetLeft;
oRect.startY = e.pageY - this.offsetTop;
bDragging = true;
}
function MouseUpEvent() {
bDragging = false;
}
function MouseOutEvent() {
document.getElementById("MouseCoords").innerHTML="";
}
function MouseMoveEvent(e) {
if (bDragging) {
oRect.w = (e.pageX - this.offsetLeft) - oRect.startX;
oRect.h = (e.pageY - this.offsetTop) - oRect.startY;
oCanvas.getContext('2d').clearRect(0,0,oCanvas.width, oCanvas.height);
var oROI = document.getElementById("btnROI");
if (oROI.checked) {
SetROI();
}
var oLayer = document.getElementById("btnLAYER");
if (oLayer.checked) {
SetLayer();
}
var oMetrics = document.getElementById("btnMetrics");
if (oMetrics.checked) {
SetMetrics();
}
}
if (bSetROI) {
DrawROI();
}
if (bSetLayers) {
DrawLayers();
}
if(bSetMetrics){
DrawMetrics();
}
// Display the current mouse coordinates.
ShowCoordinates(e);
}
function ShowCoordinates(e) {
x=e.clientX;
y=e.clientY;
document.getElementById("MouseCoords").innerHTML="(" + x + "," + y + ") " + document.getElementById('txtPatchCount').value;
}
// Interactively draw ROI rectangle(s) on the canvas.
function SetROI() {
bSetROI = true;
oROI.startX = oRect.startX;
oROI.startY = oRect.startY;
oROI.w = oRect.w;
oROI.h = oRect.h;
}
function DrawROI() {
o2DContext.lineWidth=1.5;
o2DContext.strokeStyle = '#0F0';
o2DContext.strokeRect(oROI.startX, oROI.startY, oROI.w, oROI.h);
var iPatches = document.getElementById('txtPatchCount').value;
o2DContext.beginPath();
var iTop = oROI.startY;
var iBottom = oROI.startY + oROI.h;
var iLeft = oROI.startX;
var iX = iLeft;
for (var iPatch=1; iPatch<iPatches; ++iPatch) {
iX = iLeft + iPatch*oROI.w/iPatches;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
}
o2DContext.lineWidth=0.25;
o2DContext.stroke();
}
function SetMetrics() {
bSetMetrics = true;
oMetrics.startX = oRect.startX;
oMetrics.startY = oRect.startY;
oMetrics.w = oRect.w;
oMetrics.h = oRect.h;
}
function DrawMetrics(){
o2DContext.strokeStyle = 'black';
o2DContext.strokeRect(oMetrics.startX, oMetrics.startY, oMetrics.w, oMetrics.h);
o2DContext.beginPath();
var iTop = oMetrics.startY;
var iBottom = oMetrics.startY + oMetrics.h;
var iLeft = oMetrics.startX;
var iX = iLeft;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
o2DContext.stroke();
}
// Interactively draw layer boundaries on the canvas.
function SetLayer() {
bSetLayers = true;
oLayers.length = 0;
oLayers.push(oRect.startY);
oLayers.push(oRect.startY + oRect.h);
}
function DrawLayers() {
o2DContext.lineWidth=0.25;
o2DContext.strokeStyle = '#F00';
o2DContext.beginPath();
var iY = oLayers[0];
var iLeft = 0;
var iRight = oCanvas.width;
for (var iLayer=0; iLayer<oLayers.length; ++iLayer) {
iY = oLayers[iLayer];
o2DContext.moveTo(iLeft, iY);
o2DContext.lineTo(iRight, iY);
o2DContext.stroke();
}
}
The below blog is doing the same thing but I am not sure how to add this functionality in my code.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape
Please guide me how to add the same in mine.
Really appreciate the help.
try the following link.
It is doing somewhat you want to achieve.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape

JQuery Function not be invoked through Javascript in IE7

It works perfect in all major browsers, but not in IE7.
The Java script code is:
$(function() {
var $hdVid = jQuery.noConflict();
$hdVid(function() {
$hdVid('.hd-flv-player').hdVideo();
});
});
JQuery is:
(function($) {
// plugin definition
$.fn.hdVideo = function(options) {
// build main options before element iteration
var defaults = {
theme: 'simpledark',
childtheme: ''
};
var options = $.extend(defaults, options);
// iterate and reformat each matched element
return this.each(function() {
var $hdVideo = $(this);
$hdVideo.removeAttr('controls');
//create html structure
//main wrapper
var $video_wrap=$('<div id="hd-player"></div>');
var $video_hd_html_player = $('<div id="hd_html_player"></div>').addClass('hd-video-player').addClass(options.theme).addClass(options.childtheme);
//controls wraper
var $video_controls = $('<div class="hd-video-main-control"></div><div class="hd-video-controls"><div class="hd-video-seek-container"><div class="hd-video-seek"></div></div><div class="hd-video-buffer-container"><div class="hd-video-buffer"></div></div><div class="hd-video-options cf"><a class="hd-video-play" title="Play/Pause"></a><div class="hd-video-timer"><span class="hd-video-timer-curr">00:00</span><span class="hd-video-sep"> / </span><span class="hd-video-timer-tot-time">00:00</span></div><div class="hd-full-screen"><a class="hd-full-screen-button" title="Normal/FullScreen"></a></div><div class="hd-volume-box"><div class="hd-volume-slider-container"><div class="hd-volume-slider"></div></div><a class="hd-volume-button" title="Mute/Unmute"></a><div class="hd-volume-value-slider"></div></div><div class="hd-hd-swipe"><a class="hd-hd-swipe-button" title="High Definition / Low Definition"></a></div><div class="hd-flv-html5-switch"><a title="Switch to Flash"></a></div></div></div>');
$video_wrap.append($video_hd_html_player);
$hdVideo.wrap($video_wrap);
$hdVideo.after($video_controls);
var full_screen = 0;
//get new elements
var $video_container = $hdVideo.parent('.hd-video-player');
var $video_main_control = $('.hd-video-main-control', $video_container);
$video_controls = $('.hd-video-controls', $video_container);
var $hd_play_btn = $('.hd-video-play', $video_container);
var $hd_video_seek = $('.hd-video-seek', $video_container);
var $hd_video_buffer = $('.hd-video-buffer', $video_container);
var $hd_video_timer_curr = $('.hd-video-timer-curr', $video_container);
var $hd_video_timer_tot_time = $('.hd-video-timer-tot-time', $video_container);
var $hd_volume = $('.hd-volume-slider', $video_container);
var $hd_volume_value = $('.hd-volume-value-slider', $video_container);
var $hd_volume_btn = $('.hd-volume-button', $video_container);
var $hd_hd_swipe_btn = $('.hd-hd-swipe-button', $video_container);
var $hd_full_screen_btn = $('.hd-full-screen-button', $video_container);
var $player_change_btn = $('.hd-flv-html5-switch', $video_container);
$video_controls.hide(); // keep the controls hidden
var firstTime=1;
/* Video Elements Fetching */
var videoAttr = {};
videoAttr.poster = $("video").attr("poster");
videoAttr.src = $("source").map(function() {
return $(this).attr("src");
});
videoAttr.quality = $("source").map(function() {
return $(this).attr("data-quality");
});
videoAttr.type = $("source").map(function() {
return $(this).attr("type");
});
videoAttr.codecs = $("source").map(function() {
return $(this).attr("codecs");
});
/* Video Elements Fetching Ends */
/* Poster image into screen image */
var $video_bind_pst = $('<img class="hd-vid-poster-img" src="'+videoAttr.poster+'" data-width="544" data-height="306"><div class="hd-video-main-control"></div>');
//$hdVideo.before($video_bind_pst);
//var
//width: 630px !important; height: 354px !important; top: 0px !important; left: 0px !important; max-width: 630px !important;
/* Poster image into screen image ends*/
/* Play/Pause */
var gPlay = function() {
txt = navigator.platform ;
if(txt =='iPhone'|| txt =='Linux armv7l')
{
window.location.href = videoAttr.src[0];
}
else{
if($hdVideo.attr('paused') == false) {
$hdVideo[0].pause();
$video_main_control.removeClass("hd-video-main-control-none");
}
else {
if(firstTime)
{
$hdVideo.attr('src', vidStatistics.default_vid_src);
firstTime=0;
}
$hdVideo[0].play();
$hdVideo.attr('preload', 'auto');
$video_main_control.addClass("hd-video-main-control-none");
$hdVideo.addClass("video1-visible");
}
}
return false;
};
var hd_autoply =$("video").attr("play_auto");
if(hd_autoply=="autoplay"){
$hdVideo[0].play();
$video_main_control.addClass("hd-video-main-control-none");
$hd_play_btn.addClass('hd-paused-button');
}
$video_main_control.click(gPlay);
$hd_play_btn.click(gPlay);
$hdVideo.click(gPlay);
$hdVideo.bind('play', function() {
$hd_play_btn.addClass('hd-paused-button');
return false;
});
$hdVideo.bind('pause', function() {
$hd_play_btn.removeClass('hd-paused-button');
return false;
});
$hdVideo.bind('ended', function() {
$hd_play_btn.removeClass('hd-paused-button');
$(".hd-video-main-control").removeClass('hd-video-main-control-none');
return false;
});
var gTimeFormat=function(seconds){
var m=Math.floor(seconds/60)<10?"0"+Math.floor(seconds/60):Math.floor(seconds/60);
var s=Math.floor(seconds-(m*60))<10?"0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60));
return m+":"+s;
};
/* Play/Pause */
/* Progressbar Slider */
var seeksliding;
var createSeek = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_seek.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
slide: function(){
seeksliding = true;
},
stop:function(e,ui){
seeksliding = false;
$hdVideo.attr("currentTime",ui.value);
}
});
$video_controls.show();
}
else {
setTimeout(createSeek, 150);
}
return false;
};
createSeek();
var seekUpdate = function() {
var currenttime = $hdVideo.attr('currentTime');
if(!seeksliding)
{
$hd_video_seek.slider('value', currenttime);
$hd_video_timer_curr.text(gTimeFormat(currenttime));
}
return false;
};
$hdVideo.bind('timeupdate', seekUpdate);
/* Progressbar Slider */
/* Buffer Slider */
var buffersliding;
var createBuffer = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_buffer.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
disabled: true,
slide: function(){
buffersliding = true;
},
stop:function(e,ui){
buffersliding = false;
$hdVideo.attr("buffered",ui.value).end(0);
}
});
$video_controls.show();
}
else {
setTimeout(createBuffer, 150);
}
return false;
};
createBuffer();
// var buffertime = $hdVideo.get(0).buffered.end(0);
var buffertime = $hdVideo[0].buffered.end(0);
var currenttime = $hdVideo.attr('currentTime');
if(!buffersliding)
{
if(currenttime>buffertime){
$hd_video_buffer.slider('value', currenttime);
}
else{
$hd_video_buffer.slider('value', buffertime);
}
}
return false;
};
$hdVideo.bind('timeupdate', bufferUpdate);
/* Buffer Slider end*/
/* Volume Control */
var video_volume = 1;
$hd_volume.slider({
value: 0.4,
orientation: "horizontal",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide:function(e,ui){
$hdVideo.attr('muted',false);
video_volume = ui.value;
$hdVideo.attr('volume',ui.value);
$hd_volume_btn.removeClass('hd-volume-mute');
if(ui.value*100 == 0) {
$hd_volume_btn.css('background-position', '-244px -126px');
}
else if(ui.value*100 <= 15) {
$hd_volume_btn.css('background-position', '-244px -96px');
}
else if (ui.value*100 <= 45) {
$hd_volume_btn.css('background-position', '-244px -66px');
}
else if (ui.value*100 <= 85) {
$hd_volume_btn.css('background-position', '-244px -36px');
}
else {
$hd_volume_btn.css('background-position', '-244px -6px');
}
}
});
var muteVolume = function() {
if($hdVideo.attr('muted')==true) {
$hdVideo.attr('muted', false);
$hd_volume.slider('value', video_volume);
$hd_volume_btn.removeClass('hd-volume-mute');
}else{
$hdVideo.attr('muted', true);
$hd_volume.slider('value', '0');
$hd_volume_btn.addClass('hd-volume-mute');
}
return false;
};
/* Volume Control */
/* Full Screen */
var fullScreen = function(){
if(full_screen == 0){
full_screen = 1;
$(".hd-video-player").addClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").addClass("fullscreen-video");
$(".hd-video-main-control").addClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").addClass("fullscreen-control-elements");
}
else
{
full_screen = 0;
$(".hd-video-player").removeClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").removeClass("fullscreen-video");
$(".hd-video-main-control").removeClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").removeClass("fullscreen-control-elements");
}
return false;
};
$('body').keydown(function(e){
if (e.keyCode == 27 && full_screen == 1) {
fullScreen();
}
console.log(e);
return false;
});
/* Full Screen Ends*/
/* Default Video Quality */
var defaultVideoQuality = function(videoAttr){
var vidStatistics = {};
vidStatistics.support_vid_count=0;
var i, isSupp, myVid=document.createElement('video');
for(i=videoAttr.quality.length-1; i>=0; i--)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
vidStatistics.default_vid_qty = videoAttr.quality[i];
vidStatistics.default_vid_src = videoAttr.src[i];
vidStatistics.support_vid_count++;
}
}
if(vidStatistics.default_vid_qty == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return(vidStatistics);
};
/* Default Video Quality Ends*/
/* HD Available Check */
var hdAvailableCheck = function(videoAttr){
var k=0, i, isSupp, sdSupport = 0;
var myVid=document.createElement('video');
for(i=0; i<videoAttr.quality.length; i++)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
if(videoAttr.quality[i]=="hd")
k=1;
else
sdSupport=1;
}
}
if (k==0)
$hd_hd_swipe_btn.css('display', 'none');
if (sdSupport==0)
$hd_hd_swipe_btn.css('pointer-events', 'none').css('cursor', 'default');
return false;
}
/* HD Available Check Ends*/
/* Video Quality Check*/
var videoQualityCheck = function(){
var i, $currVid, currQuality;
$currVid = $hdVideo[0].currentSrc;
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if($currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
if(currQuality == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
/* Video Quality Check Ends*/
/* Quality Swipe */
var playerstage = 0;
var hdswipe = function(){
var currVid, currExt, currVidName, currQuality, i;
if($hdVideo.attr('paused')==false)
playerstage=1;
currVid = $hdVideo[0].currentSrc;
var currVidTime = $hdVideo.attr('currentTime');
currExt = currVid.substr(currVid.lastIndexOf('.') + 1);
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if(currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
for(i=0; i<videoAttr.quality.length; i++) //Swipe the Video
{
if((currExt==videoAttr.src[i].substr(videoAttr.src[i].lastIndexOf('.') + 1))&&(currQuality!= videoAttr.quality[i]))
{
$hdVideo.attr('src', videoAttr.src[i]);
resumeCurrTime(currVidTime);
gPlay();
createSeek();
createBuffer();
playerstage=0;
break;
}
}
alert(currQuality);
if(currQuality == "sd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
var resumeCurrTime = function(currVidTime) {
if($hdVideo.attr('readyState'))
{
$hdVideo[0].currentTime = currVidTime;
}
else
setTimeout(function() { resumeCurrTime(currVidTime); }, 150);
return false;
}
/* Quality Swipe Ends */
/* HTML5 / FLV Swipe */
var playerChangeIntFn = function(){
if(full_screen==1)
fullScreen();
$hdVideo.attr('preload', 'none');
$hdVideo.load();
var trigger = "flash";
playerChange(trigger);
return false;
};
/* HTML5 / FLV Swipe Ends */
var vidStatistics = {};
vidStatistics = defaultVideoQuality(videoAttr);
hdAvailableCheck(videoAttr);
$hd_hd_swipe_btn.click(hdswipe); //HD On/Off
$hd_volume_btn.click(muteVolume); //Mute Volume
$hd_full_screen_btn.click(fullScreen); //Full Screen On/Off
$video_container.dblclick(fullScreen); //Full Screen On/Off
$player_change_btn.click(playerChangeIntFn); //Full Screen On/Off
});
};
// plugin defaults
$.fn.hdVideo.defaults = {
};
})(jQuery);
HTML is:
<video src="" width="830" height="354" class="hd-flv-player" poster="asserts/poster.png" controls="controls" data-name="demo video" data-uid="57fb2708" preload="none">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" data-quality="hd"></source>
<source src="http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4" data-quality="sd"></source>
<source src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" data-quality="hd"></source>
<source src="asserts/300_VP8.webm" data-quality="sd"></source>
</video>
Doctype: <!DOCTYPE html>
Note: I know that IE7 wont support HTML5 Video. But I just want the control code should be binded. So that I can use Flash Fall back.
Reply to your comment
That error is because of ie7 support for "myVid.canPlayType()" in
JQuery
Then that needs to be fixed, no? Even though it looks like a third-party library, you can still fix code in them, and even submit bug fixes to the developer. Maybe they even have a later version of the library out, you could check.
if (myVid.canPlayType)
will check for the existence of the function in the object. If it doesn't exist, like you said it probably doesn't support HTML video. You should then exit the plugin with an error, or have an option in the plugin which content should be used as a fallback.
DEMO

Categories

Resources