pixijs swapping out an image without it jumping - javascript

I am working on a html 5 javascript game. It has a heavily textured background. I am looking at having one 3d background item and swapping it out on the fly. So in this instance we see a room with a closed door - then when a js event is fired - the image is swapped out to show an open door.
I am trying to create the function and although I can swap the image - I am unable to stop it from jumping.
so a new image path comes in - I null and remove the old backdrop and replace it with the new. I have read about adding it to the texture cache - not sure how to do that? Its my first time using pixijs
GroundPlane.prototype.resetBackdrop = function (imagePath) {
if(this.backdrop) {
this.backdrop.alpha = 0;
this.removeChild(this.backdrop);
this.backdrop = null;
this.backdrop = PIXI.Sprite.fromImage(imagePath);
this.backdrop.anchor.x = .5;
this.backdrop.anchor.y = .5;/*
this.backdrop.scale.x = 1.2;
this.backdrop.scale.y = 1.2;*/
this.addChildAt(this.backdrop, 0);
this.backdrop.alpha = 1;
}
};

The reason for the "jump" is that the image being swapped in takes some time to load before it can be displayed on the screen.
To prevent this, you can load the image into the TextureCache ahead of time, so when you swap images, there won't be any delay.
//set the initial backdrop image
this.backdrop = PIXI.Sprite.fromImage("Image1.png");
this.backdrop.anchor.x = 0.5;
this.backdrop.anchor.y = 0.5;
this.backdrop.scale.x = 1.2;
this.backdrop.scale.y = 1.2;
//this will store the second image into the texture cache
PIXI.Texture.fromImage("Image2.png");
//if you need to keep track of when the image has finished loading,
//use a new PIXI.ImageLoader() instead.
GroundPlane.prototype.resetBackdrop = function (imagePath)
{
//Update the image Texture
this.backdrop.setTexture(PIXI.Texture.fromFrame(imagePath));
};

Related

flashing base64 image in canvas

I can't understand why when I'm creating an image from a base64 source (coming from another canvas cnvBase) it 'flashes' : the real image imgBW is OK and remains in place until a new base64 image is sended by cnvBase, but in cnvBW it appears for a fraction of a second and disappears immediately.
HTML
<canvas id="cnvBase"></canvas>
<img id="imgBW">
<canvas id="cnvBW"></canvas>
JS
function createBWImg(){
console.log('image '+imageNB.substr(0,50)) // data:image/png;base64,iVBORw0KG....
document.getElementById('imgBW').style.width = w+'px';
document.getElementById('imgBW').style.height = y+'px';
document.getElementById('imgBW').src = imageNB;
let newimage = new Image();
newimage.onload = function() {
ctxBW.drawImage(newimage, 0, 0);
};
newimage.src = imageNB;
}
Note: cnvBase sends a new image every second when User moves his smartphone (beta value):
window.addEventListener('deviceorientation', function(event) {
alpha= Math.round(event.alpha);
beta = Math.round(event.beta);
gamma= Math.round(event.gamma);
setTimeout(function() {
if (beta >= 0 && beta <= 90) {
getValues(alpha,beta,gamma);
}
}, 1000);
});
The getValues(a,b,g) function retrieves a part of the camera stream and places it in cnvBase according to the value of b
EDIT
OK, I think that image 'seems' to remain the same but in fact not. With this code, canvas keeps the right color for one second without flashing... I think something happens (but what?) during image production: something is sent to canvas (but what?).
let color;
if(b>=0 &&b<34) color='red';
if(b>=34 &&b<67) color='green';
if(b>=67 &&b<90) color='blue';
ctxBW.fillStyle = color;
ctxBW.fillRect(0, 0, w, y);
EDIT 2
More and more strange. When adding this part of code for PCs (because changing beta orientation is hard to obtain) it works perfectly: image in canvas doesn't flash and remains in place, but not on phones where it appears and disappears as soon as created (flash effect)
if(screen > 600){ // screen is screen width
setInterval(function(){
send_pseudo_beta(Math.floor((Math.random() * 10)+1)*8) // random beta
},1000);
}

Why wont my sprite appear on top of my background?

I have been practicing using sprites for a game I am going to make and have watched and read a few tutorials, I thought I was close to getting my sprite to appear so I could finally start my game but while practicing I cant get it to work, I have dont 2 seperate tutorials where I can get the sprite and the background to appear by themselfs but cannot get them to work together, I have been using EaselJS too. some of the sprite animation code has been copied from tutorials too.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>sprite prac<title>
<!-- EaselJS library -->
<script src="lib/easel.js"></script>
<script>
// Initialize on start up so game runs smoothly
function init() {
canvas = document.getElementById("canvas");
stage = new Stage(canvas);
bg = new Image();
bg.src = "img/grassbg.jpg";
bg.onload = setBG;
stage.addChild(background);
imgMonsterARun = new Image();
imgMonsterARun.onload = handleImageLoad;
imgMonsterARun.onerror = handleImageError;
imgMonsterARun.src = "img/MonsterARun.png";
stage.update();
}
function handleImageLoad(e) {
startGame();
}
// Simple function for setting up the background
function setBG(event){
var bgrnd = new Bitmap(bg);
stage.addChild(bgrnd);
stage.update();
}
function startGame() {
// create a new stage and point it at our canvas:
stage = new createjs.Stage(canvas);
// grab canvas width and height for later calculations:
screen_width = canvas.width;
screen_height = canvas.height;
// create spritesheet and assign the associated data.
var spriteSheet = new createjs.SpriteSheet({
// image to use
images: [imgMonsterARun],
// width, height & registration point of each sprite
frames: {width: 64, height: 64, regX: 32, regY: 32},
animations: {
walk: [0, 9, "walk"]
}
});
// create a BitmapAnimation instance to display and play back the sprite sheet:
bmpAnimation = new createjs.BitmapAnimation(spriteSheet);
// start playing the first sequence:
bmpAnimation.gotoAndPlay("walk"); //animate
// set up a shadow. Note that shadows are ridiculously expensive. You could display hundreds
// of animated rats if you disabled the shadow.
bmpAnimation.shadow = new createjs.Shadow("#454", 0, 5, 4);
bmpAnimation.name = "monster1";
bmpAnimation.direction = 90;
bmpAnimation.vX = 4;
bmpAnimation.x = 16;
bmpAnimation.y = 32;
// have each monster start at a specific frame
bmpAnimation.currentFrame = 0;
stage.addChild(bmpAnimation);
// we want to do some work before we update the canvas,
// otherwise we could use Ticker.addListener(stage);
createjs.Ticker.addListener(window);
createjs.Ticker.useRAF = true;
createjs.Ticker.setFPS(60);
}
//called if there is an error loading the image (usually due to a 404)
function handleImageError(e) {
console.log("Error Loading Image : " + e.target.src);
}
function tick() {
// Hit testing the screen width, otherwise our sprite would disappear
if (bmpAnimation.x >= screen_width - 16) {
// We've reached the right side of our screen
// We need to walk left now to go back to our initial position
bmpAnimation.direction = -90;
}
if (bmpAnimation.x < 16) {
// We've reached the left side of our screen
// We need to walk right now
bmpAnimation.direction = 90;
}
// Moving the sprite based on the direction & the speed
if (bmpAnimation.direction == 90) {
bmpAnimation.x += bmpAnimation.vX;
}
else {
bmpAnimation.x -= bmpAnimation.vX;
}
// update the stage:
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500" style="border: thin black solid;" ></canvas>
</body>
</html>
There are a few places where you are using some really old APIs, which may or may not be supported depending on your version of EaselJS. Where did you get the easel.js script you reference?
Assuming you have a version of EaselJS that matches the APIs you are using, there are a few issues:
You add background to the stage. There is no background, so you are probably getting an error when you add it. You already add bgrnd in the setBackground method, which should be fine. If you get an error here, then this could be your main issue.
You don't need to update the stage any time you add something, just when you want the stage to "refresh". In your code, you update after setting the background, and again immediately at the end of your init(). These will fire one after the other.
Are you getting errors in your console? That would be a good place to start debugging. I would also recommend posting code if you can to show an actual demo if you continue to have issues, which will help identify what is happening.
If you have a newer version of EaselJS:
BitmapAnimation is now Sprite, and doesn't support direction. To flip Sprites, use scaleX=-1
Ticker no longer uses addListener. Instead it uses the EventDispatcher. createjs.Ticker.addEventListener("tick", tickFunction);
You can get new versions of the CreateJS libraries at http://code.createjs.com, and you can get updated examples and code on the website and GitHub.

Using canvas to create desktop notification images, only one image works from background page

I'm having an issue while using canvas in a background page to create data URLs for desktop notifications' images.
I want to use the "image" notifications which require a 3:2 ratio to display properly. The images I want to use (from hulu.com) are a different ratio, so I decided to use the canvas element to create the corresponding data URL off of these images so that the ratio is correct. It kind of works in theory, but…
…I'm having issues if I'm creating more than one canvas/notification in the background page. One image is created properly, but the rest comes out empty.
Confusingly, opening the same background page in a new tab (i.e. exact same code) makes everything works just fine: all the notifications are created with the images loaded from hulu.com. Also, just changing the dimensions from 360x240 to 300x200 makes it work. Finally, though they're similar computers with the same Chrome version (34.0.1847.116), it works without modification at work while it doesn't on my own laptop.
I made a test extension available at the bottom of this post. Basically, it only has a generated background page. The code for that page is this:
var images = ["http://ib2.huluim.com/video/60376901?size=290x160&img=1",
"http://ib2.huluim.com/video/60366793?size=290x160&img=1",
"http://ib4.huluim.com/video/60372951?size=290x160&img=1",
"http://ib1.huluim.com/video/60365336?size=290x160&img=1",
"http://ib3.huluim.com/video/60376290?size=290x160&img=1",
"http://ib4.huluim.com/video/60377231?size=290x160&img=1",
"http://ib4.huluim.com/video/60312203?size=290x160&img=1",
"http://ib1.huluim.com/video/60376972?size=290x160&img=1",
"http://ib4.huluim.com/video/60376971?size=290x160&img=1",
"http://ib1.huluim.com/video/60376616?size=290x160&img=1"];
for (var i = 0; i < 10; i++) {
getDataURL(i);
}
/*
* Gets the data URL for an image URL
*/
function getDataURL(i) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = 360;
canvas.height = 240;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
var dataURL = canvas.toDataURL('image/png');
chrome.notifications.create('', {
type: 'image',
iconUrl: 'logo_128x128.png',
title: String(i),
message: 'message',
imageUrl: dataURL
}, function(id) {});
}
//img.src = chrome.extension.getURL('logo_128x128.png');;
img.src = images[i];
}
The commented out line for img.src = ... is a test where it loads a local file instead of a remote one. In that case, all the images are created.
The red rectangle added to the canvas is to show that it's not just the remote image that is an issue: the whole resulting canvas is empty, without any red rectangle.
If you download and add the test extension below, you should get 10 notifications but only one with an image.
Then, to open the background page in a new tab, you can inspect the background page, type this in the console:
chrome.extension.getURL('_generated_background_page.html')
and right-click the URL, and click "Open in a new Tab" (or window). Once open you should get 10 notifications that look fine.
Any idea of what is going on? I haven't been able to find any kind of limitations for background pages relevant to that. Any help would be appreciated, because this has been driving me crazy!
Files available here: https://www.dropbox.com/s/ejbh6wq0qixb7a8/canvastest.zip
edit: based on #GameAlchemist's comment, I also tried the following: same getDataURL method, but the loop wrapped inside an onload for the logo:
function loop() {
for (var i = 0; i < 10; i++) {
getDataURL(i);
}
}
var logo = new Image();
logo.onload = function () {
loop();
}
logo.src = chrome.extension.getURL('logo_128x128.png');
Remember that the create() method is asynchronous and you should use a callback with. The callback can invoke next image fetching.
I would suggest doing this in two steps:
Load all the images first
Process the image queue
The reason is that you can utilize the asynchronous image loading better this way instead of chaining the callbacks which would force you to load one and one image.
For example:
Image loader
var urls = ["http://ib2.huluim.com/video/60376901?size=290x160&img=1",
"http://ib2.huluim.com/video/60366793?size=290x160&img=1",
"http://ib4.huluim.com/video/60372951?size=290x160&img=1",
"http://ib1.huluim.com/video/60365336?size=290x160&img=1",
"http://ib3.huluim.com/video/60376290?size=290x160&img=1",
"http://ib4.huluim.com/video/60377231?size=290x160&img=1",
"http://ib4.huluim.com/video/60312203?size=290x160&img=1",
"http://ib1.huluim.com/video/60376972?size=290x160&img=1",
"http://ib4.huluim.com/video/60376971?size=290x160&img=1",
"http://ib1.huluim.com/video/60376616?size=290x160&img=1"];
var images = [], // store image objects
count = urls.length; // for loader
for (var i = 0; i < urls.length; i++) {
var img = new Image; // create image
img.onload = loader; // share loader handler
img.src = urls[i]; // start loading
images.push(img); // push image object in array
}
function loader() {
count--;
if (count === 0) process(); // all loaded, start processing
}
//TODO need error handling here as well
Fiddle with concept code for loader
Processing
Now the processing can be isolated from the loading:
function process() {
// share a single canvas (use clearRect() later if needed)
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
current = 0;
canvas.width = 360;
canvas.height = 240;
createImage(); // invoke processing for first image
function createImage() {
ctx.drawImage(images[current], 0, 0); // draw current image
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
chrome.notifications.create('', {
type : 'image',
iconUrl : 'logo_128x128.png',
title : String(i),
message : 'message',
imageUrl: canvas.toDataURL() // png is default
},
function(id) { // use callback
current++; // next in queue
if (current < images.length) {
createImage(); // call again if more images
}
else {
done(); // we're done -> continue to done()
}
});
}
}
Disclaimer: I don't have a test environment to test Chrome extensions so typos/errors may be present.
Hope this helps!

weird behavior inside canvas when animating a human stripes

this is my jsfiddle : http://jsfiddle.net/yKvuK/6/
if (keydown.right) {
characterImg.src = 'http://pixenate.com/pixenate//cache/photo_e2094a30725ccd74a6d889648d34343b.jpg';
character.CurentPos++;
character.x += character.speed;
if (character.x > CanvasWidth - character.width) { // make the character keep walking even if he step outside the canvas
character.x = 0;
}
}
if (keydown.up) {
characterImg.src = "http://pixenate.com/pixenate//cache/photo_1_5ef90294cd2afeb4486dedd663cfd872.jpg";
character.y -= character.speed;
if (character.y < 0) {
character.y = 0;
}
character.CurentPos++;
}
if (keydown.down) { //going down
characterImg.src = "http://pixenate.com/pixenate//cache/photo_1_ff6712ddd80b138f1865eb4937622d1b.jpg";
character.CurentPos++;
character.y += character.speed;
if (character.y > CanvasHeight - character.height) {
character.y = CanvasHeight - character.height;
}
}
you can see the problem when trying to move the character up and down can anyone help me ?
You need to create a new version of your images, I mean make a new png file one for each. jpg does not support transparency.
(I made on for you, you can see in the url under)
When you have the files you can do like:
var characterImgL = new Image(); // Image Left to be loaded and drawn on canvas
var characterImgR = new Image(); // Image Right to be loaded and drawn on canvas
var characterImgU = new Image(); // Image Up to be loaded and drawn on canvas
var characterImgD = new Image(); // Image Down to be loaded and drawn on canvas
...
function init() {
characterImgL.src = "http://david.blob.core.windows.net/easeljstutorials/img/MonsterARun.png";
characterImgR.src = "http://s23.postimg.org/8j8gi9owb/Monster_ARun_R.png";
characterImgU.src = "http://s23.postimg.org/8j8gi9owb/Monster_ARun_R.png";
characterImgD.src = "http://s23.postimg.org/8j8gi9owb/Monster_ARun_R.png";
characterImg = characterImgL; //Start image = Left image
}
and then on each movement you assign the characterImg to the right one.
Like
characterImg = characterImgR; if movement to right
characterImg = characterImgL; if movement to left
Check the fiddle, the left / right is working, the up, down you have to fix png for that it will take some minutes to rotate each frame.
(you can copy the .png for the right movement from the url in the fiddle)
Option 1: (the easy way)
Use as in the fiddle. Notice that the Monster_ARun_R.png image is almost correct, it has 10 images inside it and they should change position. The one you see to the left should be in the right looking to the right. The second one should be the next last (also looking to the right, ect)
Example (numbers are images):
1 2 3 4 5 6 7 8 9 10 should be 10 9 8 7 6 5 4 3 2 1 BUT looking to the right (otherwise is the same as MonsterARun.png
Option 2: (a bit more work)
If you will have Right, Left, Up & Down movement you need a different png/file for each movement. Each png file is made of several images to make an animation. The one I fixed I just flipped horizontally the original png file (like mirror view) but to be well done you need to also invert the order of each image. And then the same for up & down movement. AND all png files are horizontal. The ones you put in your fiddle are vertical you need a image like this:

Calling several functions using JavaScript's window.onload attribute

I have the following code in the index.html page of my site, which when the page loads, draws a number of images to the HTML5 canvas:
window.onload = function(){
var sources = {};
sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
sources[2] = document.getElementById("drink").src,
sources[3] = document.getElementById("food").src,
sources[4] = document.getElementById("fridge").src,
sources[5] = document.getElementById("land").src,
sources[6] = document.getElementById("money").src,
sources[7] = document.getElementById("oven").src,
sources[8] = document.getElementById("table").src,
sources[9] = document.getElementById("van").src,
sources[10] = document.getElementById("burger").src,
sources[11] = document.getElementById("chips").src,
sources[12] = document.getElementById("drink").src,
sources[13] = document.getElementById("franchiseFee").src,
sources[14] = document.getElementById("wages").src,
sources[15] = document.getElementById("admin").src,
sources[16] = document.getElementById("cleaners").src,
sources[17] = document.getElementById("electricity").src,
sources[18] = document.getElementById("insurance").src,
sources[19] = document.getElementById("manager").src,
sources[20] = document.getElementById("rates").src,
sources[21] = document.getElementById("training").src,
sources[22] = document.getElementById("water").src,
sources[23] = document.getElementById("burger").src,
sources[24] = document.getElementById("chips").src,
sources[25] = document.getElementById("drink").src,
sources[26] = document.getElementById("creditors").src,
sources[27] = document.getElementById("electricity").src,
sources[28] = document.getElementById("food").src,
sources[29] = document.getElementById("hirePurchase").src,
sources[30] = document.getElementById("loan").src,
sources[31] = document.getElementById("overdraft").src,
sources[32] = document.getElementById("payeTax").src,
sources[33] = document.getElementById("tax").src
loadImages(sources, drawImage);
};
Sources is the array that I'm using to hold the images in JavaScript so that they can be drawn to the canvas once they've been loaded from a hidden section in my HTML.
This function currently works exactly as it's intended- it has a call to the loadImages function, which loads the images from a hidden section in the HTML into the JavaScript array, and calls the drawImage function on each of the images in the array.
But I also have another function that I want to be called with the window.onload:
The function I want to add to window.onload is this:
function drawGameElements(){
/* Draw a line for the 'score bar'. */
context.moveTo(0, 25);
context.lineTo(1000, 25);
context.stroke();
/* Draw current level/ total levels on the left, and current score on the right. */
context.font = "11pt Calibri"; /* Text font & size */
context.strokeStyle = "black"; /* Font colour */
context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
context.strokeText(currentScore, 950, 15);
}
I tried adding a call to the function just below the loadImages(sources, drawImage); line in window.onload = function(){};
So that I now have:
window.onload = function(){
...
loadImages(sources, drawImage);
drawGameElements();
};
Although this partially works, in that it draws the line across the top of the canvas for the 'score bar' and writes "1/3" for the levels on the left hand side of the canvas just above the line, for some reason it doesn't draw the current score on the right hand side.
Also, as soon as I click on one of the images that's been drawn to the canvas, to drag and drop it around the canvas, the 'score bar' then disappears from the canvas completely.
Does anyone know why this is? How can I get the score bar to remain visible throughout the duration of the game, no matter what else happens on the canvas? Also, how can I get the currentScore variable to be displayed?
I would instead use a callback inside of loadImages to call drawGameElements. That way drawGameElements only runs after loadImages is finished. It sounds like you've created a race condition with your two functions.
If I where you, I would create the score bar outside of the canvas. Set its position to absolute and let it hover above the canvas at the desired location. That way you can just access it as HTML elements and do not need to worry about redrawing.
The major advantage of using HTML elements for these displays is that you don't need to redraw them, for example after moving the images around on the canvas. You also don't have to worry about how to refresh the values (on a canvas, just painting new values over the old ones will not be enough). This way you can just store the values in HTML elements and go wild on the canvas, knowing the score will always stay on top.

Categories