How to put a gif with Canvas - javascript

I'm creating a game, and in my game, when the HERO stay near the MONSTER, a gif will be showed, to scare the player. But I have no idea how to do this. I tried to put PHP or HTML code, but it doesn't works... The function is AtualizaTela2(). This is my main code:
<!DOCTYPE HTML>
<html>
<head>
<title>Hero's Escape Game</title>
<script language="JavaScript" type="text/javascript">
var objCanvas=null; // object that represents the canvas
var objContexto=null;
// Hero positioning control
var xHero=300;
var yHero=100;
// Monster positioning control
var xMonster=620;
var yMonster=0;
var imgFundo2 = new Image();
imgFundo2.src = "Images/Pista2.png";
var imgMonster = new Image();
imgMonster.src = "Images/Monster.png";
var imgHero = new Image();
imgHero.src = "Images/Hero.png";
function AtualizaTela2(){
if((xHero >= xMonster-10)&&(xHero <= xMonster + 10))
{
/*gif here*/
}
objContexto.drawImage(imgFundo2,0,0);
objContexto.drawImage(imgHero, xHero, yHero);
objContexto.drawImage(imgMonster, xMonster, yMonster);
function Iniciar(){
objCanvas = document.getElementById("meuCanvas");
objContexto = objCanvas.getContext("2d");
AtualizaTela2();
}
/* the function HeroMovement() and MonsterMovement() are not here */
}
</script>
</head>
<body onLoad="Iniciar();" onkeydown="HeroMovement(event);">
<canvas id="meuCanvas" width="1233"
height="507"
style="border:1px solid #000000;">
Seu browser não suporta o elemento CANVAS, atualize-se!!!
</canvas><BR>
</body>
</html>
This is the simplified code, because the real code is very big!
Thanks for the help! :)

Loading and playing GIF image to canvas.
Sorry answer exceeded size limit, had to remove much of the detailed code comments.
I am not going to go into details as the whole process is rather complicated.
The only way to get a GIF animated in canvas is to decode the GIF image in javascript. Luckily the format is not too complicated with data arranged in blocks that contain image size, color pallets, timing information, a comment field, and how frames are drawn.
Custom GIF load and player.
The example below contains an object called GIF that will create custom format GIF images from URLs that can play a GIF similar to how a video is played. You can also randomly access all GIF frames in any order.
There are many callbacks and options. There is basic usage information in comments and the code shows how to load the gif. There are functions to pause and play, seek(timeInSeconds) and seekFrame(frameNumber), properties to control playSpeed and much more. There are no shuttling events as access is immediate.
var myGif = GIF();
myGif.load("GIFurl.gif");
Once loaded
ctx.drawImage(myGif.image,0,0); // will draw the playing gif image
Or access the frames via the frames buffer
ctx.drawImage(myGif.frames[0].image,0,0); // draw frame 0 only.
Go to the bottom of the GIF object to see all the options with comments.
The GIF must be same domain or have CORS header
The gif in he demo is from wiki commons and contains 250+ frames, some low end devices will have trouble with this as each frame is converted to a full RGBA image making the loaded GIF significantly larger than the gif file size.
The demo
Loads the gif displaying the frames and frame count as loaded.
When loaded 100 particles each with random access frames playing at independent speeds and independent directions are displayed in the background.
The foreground image is the gif playing at the frame rate embedded in the file.
Code is as is, as an example only and NOT for commercial use.
const ctx = canvas.getContext("2d");
var myGif;
// Can not load gif cross domain unless it has CORS header
const gifURL = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Wax_fire.gif";
// timeout just waits till script has been parsed and executed
// then starts loading a gif
setTimeout(()=>{
myGif = GIF(); // creates a new gif
myGif.onerror = function(e){
console.log("Gif loading error " + e.type);
}
myGif.load(gifURL);
},0);
// Function draws an image
function drawImage(image,x,y,scale,rot){
ctx.setTransform(scale,0,0,scale,x,y);
ctx.rotate(rot);
ctx.drawImage(image,-image.width / 2, -image.height / 2);
}
// helper functions
const rand = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const setOf =(c,C)=>{var a=[],i=0;while(i<c){a.push(C(i++))}return a};
const eachOf =(a,C)=>{var i=0;const l=a.length;while(i<l && C(a[i],i++,l)!==true);return i};
const mod = (v,m) => ((v % m) + m) % m;
// create 100 particles
const particles = setOf(100,() => {
return {
x : rand(innerWidth),
y : rand(innerHeight),
scale : rand(0.15, 0.5),
rot : rand(Math.PI * 2),
frame : 0,
frameRate : rand(-2,2),
dr : rand(-0.1,0.1),
dx : rand(-4,4),
dy : rand(-4,4),
};
});
// Animate and draw 100 particles
function drawParticles(){
eachOf(particles, part => {
part.x += part.dx;
part.y += part.dy;
part.rot += part.dr;
part.frame += part.frameRate;
part.x = mod(part.x,innerWidth);
part.y = mod(part.y,innerHeight);
var frame = mod(part.frame ,myGif.frames.length) | 0;
drawImage(myGif.frames[frame].image,part.x,part.y,part.scale,part.rot);
});
}
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
// main update function
function update(timer) {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
if (w !== innerWidth || h !== innerHeight) {
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
} else {
ctx.clearRect(0, 0, w, h);
}
if(myGif) { // If gif object defined
if(!myGif.loading){ // if loaded
// draw random access to gif frames
drawParticles();
drawImage(myGif.image,cw,ch,1,0); // displays the current frame.
}else if(myGif.lastFrame !== null){ // Shows frames as they load
ctx.drawImage(myGif.lastFrame.image,0,0);
ctx.fillStyle = "white";
ctx.fillText("GIF loading frame " + myGif.frames.length ,10,21);
ctx.fillText("GIF loading frame " + myGif.frames.length,10,19);
ctx.fillText("GIF loading frame " + myGif.frames.length,9,20);
ctx.fillText("GIF loading frame " + myGif.frames.length,11,20);
ctx.fillStyle = "black";
ctx.fillText("GIF loading frame " + myGif.frames.length,10,20);
}
}else{
ctx.fillText("Waiting for GIF image ",10,20);
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
/*============================================================================
Gif Decoder and player for use with Canvas API's
**NOT** for commercial use.
To use
var myGif = GIF(); // creates a new gif
var myGif = new GIF(); // will work as well but not needed as GIF() returns the correct reference already.
myGif.load("myGif.gif"); // set URL and load
myGif.onload = function(event){ // fires when loading is complete
//event.type = "load"
//event.path array containing a reference to the gif
}
myGif.onprogress = function(event){ // Note this function is not bound to myGif
//event.bytesRead bytes decoded
//event.totalBytes total bytes
//event.frame index of last frame decoded
}
myGif.onerror = function(event){ // fires if there is a problem loading. this = myGif
//event.type a description of the error
//event.path array containing a reference to the gif
}
Once loaded the gif can be displayed
if(!myGif.loading){
ctx.drawImage(myGif.image,0,0);
}
You can display the last frame loaded during loading
if(myGif.lastFrame !== null){
ctx.drawImage(myGif.lastFrame.image,0,0);
}
To access all the frames
var gifFrames = myGif.frames; // an array of frames.
A frame holds various frame associated items.
myGif.frame[0].image; // the first frames image
myGif.frame[0].delay; // time in milliseconds frame is displayed for
Gifs use various methods to reduce the file size. The loaded frames do not maintain the optimisations and hold the full resolution frames as DOM images. This mean the memory footprint of a decode gif will be many time larger than the Gif file.
*/
const GIF = function () {
// **NOT** for commercial use.
var timerID; // timer handle for set time out usage
var st; // holds the stream object when loading.
var interlaceOffsets = [0, 4, 2, 1]; // used in de-interlacing.
var interlaceSteps = [8, 8, 4, 2];
var interlacedBufSize; // this holds a buffer to de interlace. Created on the first frame and when size changed
var deinterlaceBuf;
var pixelBufSize; // this holds a buffer for pixels. Created on the first frame and when size changed
var pixelBuf;
const GIF_FILE = { // gif file data headers
GCExt : 0xF9,
COMMENT : 0xFE,
APPExt : 0xFF,
UNKNOWN : 0x01, // not sure what this is but need to skip it in parser
IMAGE : 0x2C,
EOF : 59, // This is entered as decimal
EXT : 0x21,
};
// simple buffered stream used to read from the file
var Stream = function (data) {
this.data = new Uint8ClampedArray(data);
this.pos = 0;
var len = this.data.length;
this.getString = function (count) { // returns a string from current pos of len count
var s = "";
while (count--) { s += String.fromCharCode(this.data[this.pos++]) }
return s;
};
this.readSubBlocks = function () { // reads a set of blocks as a string
var size, count, 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 = [];
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 frames pixels
// this needs to be optimised.
// minSize is the min dictionary as powers of two
// size and data is the compressed pixels
function lzwDecode(minSize, data) {
var i, pixelPos, pos, clear, eod, size, done, dic, code, last, d, len;
pos = pixelPos = 0;
dic = [];
clear = 1 << minSize;
eod = clear + 1;
size = minSize + 1;
done = false;
while (!done) { // JavaScript optimisers like a clear exit though I never use 'done' apart from fooling the optimiser
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;
} else {
if (code === eod) { 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++ }
}
}
};
function parseColourTable(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;
}
function parse (){ // read the header. This is the starting point of the decode and async calls parseBlock
var bitField;
st.pos += 6;
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) { gif.globalColourTable = parseColourTable(gif.globalColourCount) } // global colour flag
setTimeout(parseBlock, 0);
}
function parseAppExt() { // 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
}
};
function parseGCExt() { // 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++;
};
function parseImg() { // 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) { // create the buffer if size changed or undefined.
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
};
function processFrame(frame) { // creates a RGBA canvas image from the indexed pixel data.
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") { doOnloadEvent() }// if !waitTillDone the call onload now after first frame is loaded
};
// **NOT** for commercial use.
function finnished() { // 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() }
}
function canceled () { // called if the load has been cancelled
finnished();
if (typeof gif.cancelCallback === "function") { (gif.cancelCallback.bind(gif))({ type : 'canceled', path : [gif] }) }
}
function parseExt() { // parse extended blocks
const blockID = st.data[st.pos++];
if(blockID === GIF_FILE.GCExt) { parseGCExt() }
else if(blockID === GIF_FILE.COMMENT) { gif.comment += st.readSubBlocks() }
else if(blockID === GIF_FILE.APPExt) { parseAppExt() }
else {
if(blockID === GIF_FILE.UNKNOWN) { st.pos += 13; } // skip unknow block
st.readSubBlocks();
}
}
function parseBlock() { // parsing the blocks
if (gif.cancel !== undefined && gif.cancel === true) { canceled(); return }
const blockId = st.data[st.pos++];
if(blockId === GIF_FILE.IMAGE ){ // image block
parseImg();
if (gif.firstFrameOnly) { finnished(); return }
}else if(blockId === GIF_FILE.EOF) { finnished(); return }
else { parseExt() }
if (typeof gif.onprogress === "function") {
gif.onprogress({ bytesRead : st.pos, totalBytes : st.data.length, frame : gif.frames.length });
}
setTimeout(parseBlock, 0); // parsing frame async so processes can get some time in.
};
function cancelLoad(callback) { // cancels the loading. This will cancel the load before the next frame is decoded
if (gif.complete) { return false }
gif.cancelCallback = callback;
gif.cancel = true;
return true;
}
function error(type) {
if (typeof gif.onerror === "function") { (gif.onerror.bind(this))({ type : type, path : [this] }) }
gif.onload = gif.onerror = undefined;
gif.loading = false;
}
function doOnloadEvent() { // fire onload event if set
gif.currentFrame = 0;
gif.nextFrameAt = gif.lastFrameAt = new Date().valueOf(); // just sets the time now
if (typeof gif.onload === "function") { (gif.onload.bind(gif))({ type : 'load', path : [gif] }) }
gif.onerror = gif.onload = undefined;
}
function dataLoaded(data) { // Data loaded create stream and parse
st = new Stream(data);
parse();
}
function loadGif(filename) { // starts the load
var ajax = new XMLHttpRequest();
ajax.responseType = "arraybuffer";
ajax.onload = function (e) {
if (e.target.status === 404) { error("File not found") }
else if(e.target.status >= 200 && e.target.status < 300 ) { dataLoaded(ajax.response) }
else { error("Loading error : " + e.target.status) }
};
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);
gif.currentFrame = frame % gif.frames.length;
if (gif.playing) { playing() }
else { gif.image = gif.frames[gif.currentFrame].image }
}
function seek(time) { // time in Seconds // seek to frame that would be displayed at time
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;
} else {
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;
}
/*=========================================================================
End of gif reader
*/
const mouse = {
bounds: null,
x: 0,
y: 0,
button: false
};
function mouseEvents(e) {
const m = mouse;
m.bounds = canvas.getBoundingClientRect();
m.x = e.pageX - m.bounds.left - scrollX;
m.y = e.pageY - m.bounds.top - scrollY;
mouse.x = e.pageX;
m.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : m.button;
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
canvas {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas"></canvas>
NOTES
This works for 99% of gifs. Occasionally you will find a gif that does not play correctly. Reason: (I never bothered to find out). Fix: re-encode gif using modern encoder.
There are some minor inconsistencies that need fixing. In time I will provide a codePen example with ES6 and improved interface. Stay tuned.

Here ya go:
You will need to exctract each frames and make an array out of them
split frames: http://gifgifs.com/split/
easier if you have urls or path like http://lol.com/Img1.png ...... http://lol.com/Img27.png with which you can do a simple loop like this:
var Img = [];
for (var i = 0; i < 28; i++) {
Img[i] = new Image();
Img[i].src = "http://lol.com/Img"+i+".png";
}
function drawAnimatedImage(arr,x,y,angle,factor,changespeed) {
if (!factor) {
factor = 1;
}
if (!changespeed) {
changespeed = 1;
}
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle * Math.PI / 180);
if (!!arr[Math.round(Date.now()/changespeed) % arr.length]) {
ctx.drawImage(arr[Math.round(Date.now()/changespeed) % arr.length], -(arr[Math.round(Date.now()/changespeed) % arr.length].width * factor / 2), -(arr[Math.round(Date.now()/changespeed) % arr.length].height * factor / 2), arr[Math.round(Date.now()/changespeed) % arr.length].width * factor, arr[Math.round(Date.now()/changespeed) % arr.length].height * factor);
}
ctx.restore();
}
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
var waitingWolf = [];
var url = ["https://i.imgur.com/k3T7psX.gif","https://i.imgur.com/CTSC8FC.gif","https://i.imgur.com/6NHLWKK.gif","https://i.imgur.com/U1u04sY.gif","https://i.imgur.com/4695vnQ.gif","https://i.imgur.com/oDO0YWT.gif","https://i.imgur.com/LqptRh1.gif","https://i.imgur.com/6gTxvul.gif","https://i.imgur.com/ULN5mqK.gif","https://i.imgur.com/RACB9WM.gif","https://i.imgur.com/4TZ6kNi.gif","https://i.imgur.com/9VvlzhK.gif","https://i.imgur.com/nGUnsfW.gif","https://i.imgur.com/2h8vLjK.gif","https://i.imgur.com/ZCdKkF1.gif","https://i.imgur.com/wZmWrYP.gif","https://i.imgur.com/4lhjVSz.gif","https://i.imgur.com/wVO0PbE.gif","https://i.imgur.com/cgGn5tV.gif","https://i.imgur.com/627gH5Y.gif","https://i.imgur.com/sLDSeS7.gif","https://i.imgur.com/1i1QNAs.gif","https://i.imgur.com/V3vDA1A.gif","https://i.imgur.com/Od2psNo.gif","https://i.imgur.com/WKDXFdh.gif","https://i.imgur.com/RlhIjaM.gif","https://i.imgur.com/293hMnm.gif","https://i.imgur.com/ITm0ukT.gif"]
function setup () {
for (var i = 0; i < 28; i++) {
waitingWolf[i] = new Image();
waitingWolf[i].src = url[i];
}
}
setup();
function yop() {
ctx.clearRect(0,0,1000,1000)
if (waitingWolf.length == 28) {
drawAnimatedImage(waitingWolf,300,100,0,1,60)
}
requestAnimationFrame(yop);
}
requestAnimationFrame(yop);
<canvas id="myCanvas" width="1000" height="1000">
</canvas>

You can use Gify & gifuct-js projects on Github.
First, download your Animated gif and prepare the images you need to do this on page load.
var framesArray;
var currentFrame = 0;
var totalFrames = null;
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.gif", true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if(gify.isAnimated(arrayBuffer)){
var gif = new GIF(arrayBuffer);
framesArray = gif.decompressFrames(true);
totalFrames = framesArray.length;
}
};
oReq.send(null);
When you want your animation to show so in your draw loop
if((xHero >= xMonster-10)&&(xHero <= xMonster + 10)){
// you need to work out from your frame rate when you should increase current frame
// based on the framerate of the gif image using framesArray[currentFrame].delay
// auto-detect if we need to jump to the first frame in the loop
// as we gone through all the frames
currentFrame = currentFrame % totalFrames;
var frame = framesArray[currentFrame];
var x,y;
// get x posstion as an offset from xHero
// get y posstion as an offset from yHero
objContexto.putImageData(frame.patch,x,y);
}
Please note this code is not tested I built following the documentation of the 2 projects so it might be a little wrong but it shows roughly how it is possible,
the 3rd link is the online contents of the demo folder for the gitfuct-js library
https://github.com/rfrench/gify
https://github.com/matt-way/gifuct-js
http://matt-way.github.io/gifuct-js/

It is not possible to simply draw a .gif (animated!) on the <canvas> element.
You have two options.
a) you can append the HTML with a <div> to which you append the .gif (via <img> node) and then layer the via z-Index and css top/left over the <canvas>, at the correct position. It will mess up with mouse events eventually tho, which can be solved by event propagation. I would consider this a poor mans solution.
b) You need to learn how to animate stuff. Look up window.requestAnimationFrame method. Doing so will allow you to animate on the <canvas>, which can emulate the .gif behavior you are looking for. It will however be a bit complex at your current level i think.
You can draw the .gif on the canvas like the above poster described. However, it will be 100 % static, like a .jpg or .png in that case, unless you manage to dissolve the .gif into its frames and still use the window.requestAnimationFrame method.
Basicly, if you want the animated behavior of a .gif, you will need to make major adjustments.

Simply draw your image on the canvas at whatever position you want to insert your gif. I'll assume you want to insert your gif in the canvas meuCanvas.
So:
if((xHero >= xMonster-10)&&(xHero <= xMonster + 10))
{
var ctx = document.getElementById('meuCanvas').getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = 'http://media3.giphy.com/media/kEKcOWl8RMLde/giphy.gif';
}

I'm also not quite sure what your problem is, but instead of:
if((xHero >= xMonster-10)||(xHero <= xMonster + 10))
{
/*gif here*/
}
you probably want:
if (xHero >= xMonster-10 && xHero <= xMonster + 10)
{
/*gif here*/
}
|| means OR
&& means AND
In your code using OR makes the condition always true; that's probably not what you want.

Related

How to detect, that drawing a canvas object is finished?

I have following JS code (found here, on stackoverflow, and a little-bit modded), which resize image on client side using canvas.
function FileListItem(a) {
// Necesary to proper-work of CatchFile function (especially image-resizing).
// Code by Jimmy Wärting (https://github.com/jimmywarting)
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError('expected argument to FileList is File or array of File objects')
for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
function CatchFile(obj) {
// Based on ResizeImage function.
// Original code by Jimmy Wärting (https://github.com/jimmywarting)
var file = obj.files[0];
// Check that file is image (regex)
var imageReg = /[\/.](gif|jpg|jpeg|tiff|png|bmp)$/i;
if (!file) return
var uploadButtonsDiv = document.getElementById('upload_buttons_area');
// Check, that it is first uploaded file, or not
// If first, draw a div for showing status
var uploadStatusDiv = document.getElementById('upload_status_area');
if (!uploadStatusDiv) {
var uploadStatusDiv = document.createElement('div');
uploadStatusDiv.setAttribute('class', 'upload-status-area');
uploadStatusDiv.setAttribute('id', 'upload_status_area');
uploadButtonsDiv.parentNode.insertBefore(uploadStatusDiv, uploadButtonsDiv.nextSibling);
// Draw sub-div for each input field
var i;
for (i = 0; i < 3; i++) {
var uploadStatus = document.createElement('div');
uploadStatus.setAttribute('class', 'upload-status');
uploadStatus.setAttribute('id', ('upload_status_id_commentfile_set-' + i + '-file'));
uploadStatusDiv.append(uploadStatus);
}
}
var canvasDiv = document.getElementById('canvas-area');
var currField = document.getElementById(obj.id);
var currFieldLabel = document.getElementById(('label_' + obj.id));
// Main image-converting procedure
if (imageReg.test(file.name)) {
file.image().then(img => {
const canvas = document.createElement('canvas')
canvas.setAttribute('id', ('canvas_' + obj.id));
const ctx = canvas.getContext('2d')
const maxWidth = 1600
const maxHeight = 1200
// Calculate new size
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height)
const width = img.width * ratio + .5|0
const height = img.height * ratio + .5|0
// Resize the canvas to the new dimensions
canvas.width = width
canvas.height = height
// Drawing canvas-object is necessary to proper-work
// on mobile browsers.
// In this case, canvas is inserted to hidden div (display: none)
ctx.drawImage(img, 0, 0, width, height)
canvasDiv.appendChild(canvas)
// Get the binary (aka blob)
canvas.toBlob(blob => {
const resizedFile = new File([blob], file.name, file)
const fileList = new FileListItem(resizedFile)
// Temporary remove event listener since
// assigning a new filelist to the input
// will trigger a new change event...
obj.onchange = null
obj.files = fileList
obj.onchange = CatchFile
}, 'image/jpeg', 0.70)
}
)
// If file is image, during conversion show status
function ShowConvertConfirmation() {
if (document.getElementById('canvas_' + obj.id)) {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return true;
}
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return false;
}
}
// Loop ShowConvertConfirmation function untill return true (file is converted)
var convertConfirmationLoop = setInterval(function() {
var isConfirmed = ShowConvertConfirmation();
if (!isConfirmed) {
ShowConvertConfirmation();
}
else {
// Break loop
clearInterval(convertConfirmationLoop);
}
}, 2000); // Check every 2000ms
}
// If file is not an image, show status with filename
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Dodano plik ' + file.name + '</font>';
//uploadStatusDiv.append(uploadStatus);
}
}
Canvas is drawn in hidden div:
<div id="canvas-area" style="overflow: hidden; height: 0;"></div>
I am only detect, that div canvas-area is presented and basing on this, JS append another div with status.
Unfortunatelly on some mobile devices (mid-range smartphones), message will be showed before finish of drawing (it is wrong). Due to this, some uploaded images are corrupted or stay in original size.
How to prevent this?
Everything that should happen after the image has loaded, should be executed within the then callback, or called from within it.
It is important to realise that the code that is not within that callback will execute immediately, well before the drawing has completed.

How to add a 16x16 grid of pseudo-random tiles as a background in canvas (or other web language)

I have recently been working on a web based project using canvas on HTML5. The program consists of a 16x16 grid of tiles that have been pseudo-randomly generated. I am relatively new to canvas, but have built this program in several other environments, none of which however compile successfully to a web based language. this is the main code section that is giving me bother:
var A = 8765432352450986;
var B = 8765432352450986;
var M = 2576436549074795;
var X = 1;
var rx = 0;
var ry = 0;
this.image = new Image();
var i = 0;
var ii = 0;
while(i < 16)
{
while(ii < 16)
{
this.image = new Image();
this.image.src = "textures/grass.png";
x = (((A*X)+B)%M)%M;
if((x/2)%1 == 0)
{
this.image.src = "textures/grass.png";
}
if((x/8)%1 == 0)
{
this.image.src = "textures/hill.png";
}
if((x/21)%1 == 0)
{
this.image.src = "textures/trees.png";
}
if((x/24)%1 == 0)
{
this.image.src = "textures/sea.png";
}
if((x/55)%1 == 0)
{
this.image.src = "textures/mountain.png";
}
if((x/78)%1 == 0)
{
this.image.src = "textures/lake.png";
}
if((x/521)%1 == 0)
{
this.image.src = "textures/volcano.png";
}
if((x/1700)%1 == 0)
{
this.image.src = "textures/shrine.png";
}
if((x/1890)%1 == 0)
{
this.image.src = "textures/outpost.png";
}
if((x/1999)%1 == 0)
{
this.image.src = "textures/civ.png";
}
ctx = myGameArea.context;
ctx.drawImage(this.image,rx, ry, 20, 20);
ii ++;
rx += 20;
}
i ++;
rx = 0;
ry += 16;
}
I would like canvas to draw along the lines of this code above, effectively generating a grid like this
pre generated grid image
(please try and ignore the obvious bad tile drawings, I planned on either finding an artist or trying slightly harder on them when I get the game fully working.)
The black square is a separate movable object. I haven't got as far as implementing it in this version, but if you have any suggestions for it please tell me
in the full html file I have now, the canvas renders but none of the background (using the w3schools tutorials, I can make objects render however)
In short: how do I render a background consisting of a 16x16 grid of pseudo-random tiles on an event triggered or on page loaded, using canvas or if that does not work another web based technology
Thank you for your time.
A few problems but the main one is that you need to give an image some time to load before you can draw it to the canvas.
var image = new Image();
image.src = "image.png";
// at this line the image may or may not have loaded.
// If not loaded you can not draw it
To ensure an image has loaded you can add a onload event handler to the image
var image = new Image();
image.src = "image.png";
image.onload = function(){ ctx.drawImage(image,0,0); }
The onload function will be called after all the current code has run.
To load many images you want to know when all have loaded. One way to do this is to count the number of images you are loading, and then use the onload to count the number of images that have loaded. When the loaded count is the same as the loading count you know all have loaded and can then call a function to draw what you want with the images.
// Array of image names
const imageNames = "grass,hill,trees,sea,mountain,lake,volcano,shrine,outpost,civ".split(",");
const images = []; // array of images
const namedImages = {}; // object with named images
// counts of loaded and waiting toload images
var loadedCount = 0;
var imageCount = 0;
// tile sizes
const tileWidth = 20;
const tileHeight = 20;
// NOT SURE WHERE YOU GOT THIS FROM so have left it as you had in your code
// Would normally be from a canvas element via canvasElement.getContext("2d")
var ctx = myGameArea.context;
// seeded random function encapsulated in a singleton
// You can set the seed by passing it as an argument rand(seed) or
// just get the next random by not passing the argument. rand()
const rand = (function(){
const A = 8765432352450986;
const B = 8765432352450986; // This value should not be the same as A?? left as is so you get the same values
const M = 2576436549074795;
var seed = 1;
return (x = seed) => seed = ((A * x) + B) % M;
}());
// function loads an image with name
function addImage(name){
const image = new Image;
image.src = "textures/" + name + ".png";
image.onload = () => {
loadedCount += 1;
if(loadedCount === imageCount){
if(typeof allImagesLoaded === "function"){
allImagesLoaded();
}
}
}
imageCount += 1;
images.push(image);
namedImages[name] = image;
}
imageNames.forEach(addImage); // start loading all the images
// This function draws the tiles
function allImagesLoaded(){ /// function that is called when all the images have been loaded
var i, x, y, image;
for(i = 0; i < 256; i += 1){ // loop 16 by 16 times
ctx.drawImage(
images[Math.floor(rand()) % images.length]; //random function does not guarantee an integer so must floor
(i % 16) * tileWidth, // x position
Math.floor(i / 16) * tileHeight, // y position
tileWidth, tileHeight // width and height
);
}
}

THREE.js - Updating BufferGeometry position twice, causes my FPS to suffer

I have an array of TubeBufferGeometrys that im making animate to look as if they're growing out in length. When the animation runs the first time, it works really smoothly at 60fps. But once i set the geometrys position attributes back to zero, the FPS drop to 30.
Ive isolated my animation to run and then rerun once it finished with only the below changing. Heres the basics of my code:
Animation control view
stop() {
this.play = false;
// Start it again
setTimeout(() => {
let i = this.tubeCount;
while (i--) {
this.tubes[i].lastSegmentSet = 0;
this.tubes[i].updateToPercent(0);
}
this.elapsedTime = 0;
this.startTime = Date.now();
this.play = true;
}, 2000)
}
update() {
requestAnimationFrame(this.animate);
// ..render stuff + composer that ive disabled without effect
if (this.play) {
let percent = (Date.now() - this.startTime) / ANIMATE_DURATION;
if (percent >= 1) {
this.stop();
}
let i = this.lineCount;
while (i--) {
this.tubes[i].updateToPercent(percent);
}
}
}
Tube class (The main animation code)
constructor() {
//..other stuff
this.lastSegmentSet = 0;
}
// I first build the paths, then store the position data to use later to animate to. Then i set all the position data to zero
storeVerticies() {
this.positions = this.tube.geometry.attributes.position.array.slice(0);
const length = this.tube.geometry.attributes.position.array.length;
this.tube.geometry.attributes.position.array = new Float32Array(length);
}
setSegment(segment) {
this.setSegmentTo(segment, segment);
}
setSegmentTo(segment, target) {
let position = this.tube.geometry.attributes.position.array;
let startPoint = segment * JOINT_DATA_LENGTH; //JOINT_DATA_LENGTH is the number of values in the buffer geometry to update a segment
let targetPoint = target * JOINT_DATA_LENGTH;
let n = JOINT_DATA_LENGTH;
while (n--) {
position[startPoint + n] = this.positions[targetPoint + n];
}
}
updateToPercent(percent) {
let endSegment = Math.floor(percent * this.segmentCount);
while (this.lastSegmentSet <= endSegment) {
this.setSegment(this.lastSegmentSet++);
}
let n = this.lastSegmentSet;
while (n <= this.segmentCount + 1) {
this.setSegmentTo(n++, this.lastSegmentSet);
}
this.tube.geometry.attributes.position.needsUpdate = true;
}
Will put bounty when possible

Pixi.js keeps accelerating on page refresh

These are my references created in pixi.js here:
http://brekalo.info/en/reference
If we go to references it loads pixiJS and everything works fine on first load! Then, if we go to another page let's say: http://brekalo.info/en/contact, and the go back to references again - now my references have accelerated text movement and rotation and it keeps accelerate on each reference page load!
Here is my javascript/pixi code below:
function initiatePixi() {
Object.keys(PIXI.utils.TextureCache).forEach(function(texture) {
PIXI.utils.TextureCache[texture].destroy(true);}
);
// create an new instance of a pixi stage
var container = new PIXI.Container();
// create a renderer instance.
renderer = PIXI.autoDetectRenderer(frameWidth, frameHeight, transparent = false, antialias = true);
// set renderer frame background color
renderer.backgroundColor = 0xFFFFFF;
// add the renderer view element to the DOM
document.getElementById('pixi-frame').appendChild(renderer.view);
// create references
createReferences(animate); // callback to animate frame
function createReferences(callback) {
// Create text container
textContainer = new PIXI.Container();
textContainer.x = 0;
textContainer.y = 0;
for (i = 0; i < references.length; i++) {
var style = {
font:"22px Verdana",
fill:getRandomColor()
};
var text = new PIXI.Text(references[i], style);
text.x = getRandomInteger(20, 440); // text position x
text.y = getRandomInteger(20, 440); // text position y
text.anchor.set(0.5, 0.5); // set text anchor point to the center of text
text.rotation = getRandomInteger(0, rotationLockDeg) * 0.0174532925; // set text rotation
// make the text interactive
text.interactive = true;
// create urls on text click
text.on("click", function (e) {
var win = window.open("http://" + this.text, '_blank');
win.focus();
});
textContainer.addChild(text);
rotateText(); // rotate text each second
}
container.addChild(textContainer);
// callback
if (callback && typeof(callback) === "function") {
callback();
}
}
function animate() {
requestAnimationFrame(animate);
// render the stage
renderer.render(container);
}
function rotateText() {
var rotateTimer = setInterval(function () {
for (var key in textContainer.children) { // loop each text object
var text = textContainer.children[key];
if(text.rotation / 0.0174532925 < -rotationLockDeg || text.rotation / 0.0174532925 > rotationLockDeg) {
if(text.rotation / 0.0174532925 < -rotationLockDeg)
text.rotation = -rotationLockRad;
if(text.rotation / 0.0174532925 > rotationLockDeg)
text.rotation = rotationLockRad;
rotation = -rotation;
}
text.rotation += rotation; // rotate text by rotate speed in degree
if(text.x < 0 || text.x > 460)
dx = -dx;
if(text.y < 0 || text.y > 460)
dy = -dy;
text.x += dx;
text.y += dy;
}
}, 75);
}
// get random integer between given range (eg 1-10)
function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// random hex color generator
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Thanks in advance!
:: cheers ::
Josip
To expand #Cristy's comment to an answer:
The answer lies in the same reason as why your question title is wrong: There is indeed NO page refresh when doing what you describe. If there were, you wouldn't have that problem in the first place. Try it out, hit F5 a few times on you animated page, it will stay the same speed.
The reason is that you are running a angular based single page application, and only exchange the loaded view content on a route change. This does not stop your already running animation code from continuing to run in the background while you navigate to another view, so that when you return to the animated tab you will create another set of interval timers for your animation, which will result in more executions and thus a visually faster animation.
#Cristy thanks for the advice!
Here is how I manage to solve this..
I put one property in my pixi-parameters.js:
pixiWasLoaded = false;
Then, when I call initiatePixi() function, I set:
pixiWasLoaded = true;
Now in my controllers.js I have this piece of code:
.run( function($rootScope, $location, $window) {
$rootScope.$watch(function() {
return $location.path();
},
function(page){
if(page == "/hr/reference" || page == "/en/references"){
if($window.pixiWasLoaded)
$window.addRendererElementToDOM();
else
loadReferences();
}
});
});
It checks if references page is loaded and then uses $window to find my global variable "pixiWasLoaded" and if it's not loaded then it loads PixiJS using loadReferences() function.. and if is already loaded it calls my part of code to add render-view to DOM so my animate function can render it..
:: cheers ::
Josip

My javascript canvas map script and poor performance

Basically below is my script for a prototype which uses 128x128 tiles to draw a map on a canvas which user can drag to move around.
Script does work. However I have a few problems to be solved:
1. Poor performance and I can't figure out why.
2. I am missing a method to buffer the tiles before the actual drawing.
3. If you notice any other issues also that could help me to make things run more smoothly it would be fantastic.
Some explanations for the script:
variables
coordinates - Defines the actual images to be displayed. Image file names are type of '0_1.jpg', where 0 is Y and 1 is X.
mouse_position - As name says, is keeping record of mouse position.
position - This is a poorly named variable. It defines the position of the context drawn on canvas. This changes when user drags the view.
Any assistance would be appreciated greatly. Thank you.
var coordinates = [0, 0];
var mouse_position = [0, 0];
var position = [-128, -128];
var canvas = document.getElementById('map_canvas');
var context = canvas.getContext('2d');
var buffer = [];
var buffer_x = Math.floor(window.innerWidth/128)+4;
var buffer_y = Math.floor(window.innerHeight/128)+4;
var animation_frame_request = function() {
var a = window.requestAnimationFrame;
var b = window.webkitRequestAnimationFrame;
var c = window.mozRequestAnimationFrame;
var d = function(callback) {
window.setTimeout(callback, 1000/60);
}
return a || b || c || d;
}
var resizeCanvas = function() {
window.canvas.width = window.innerWidth;
window.canvas.height = window.innerHeight;
window.buffer_x = Math.floor(window.innerWidth/128)+4;
window.buffer_y = Math.floor(window.innerHeight/128)+4;
window.buffer = [];
for (row = 0; row < window.buffer_y; row++) {
x = [];
for (col = 0; col < window.buffer_x; col++) {
x.push(new Image());
}
window.buffer.push(x);
}
}
var render = function() {
animation_frame_request(render);
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
cy = window.coordinates[1]+row;
cx = window.coordinates[0]+col;
window.buffer[row][col].src = 'map/'+cy+'_'+cx+'.jpg';
}
}
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
window.context.drawImage(window.buffer[row][col],
window.position[0]+col*128,
window.position[1]+row*128, 128, 128);
}
}
}
var events = function() {
window.canvas.onmousemove = function(e) {
if (e['buttons'] == 1) {
window.position[0] += (e.clientX-window.mouse_position[0]);
window.position[1] += (e.clientY-window.mouse_position[1]);
if (window.position[0] >= 0) {
window.position[0] = -128;
window.coordinates[0] -= 1;
} else if (window.position[0] < -128) {
window.position[0] = 0;
window.coordinates[0] += 1;
}
if (window.position[1] >= 0) {
window.position[1] = -128;
window.coordinates[1] -= 1;
} else if (window.position[1] < -128) {
window.position[1] = 0;
window.coordinates[1] += 1;
}
render();
}
window.mouse_position[0] = e.clientX;
window.mouse_position[1] = e.clientY;
}
}
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('load', resizeCanvas, false);
window.addEventListener('mousemove', events, false);
resizeCanvas();
To get better performance you should avoid changing the src of img nodes and move them around instead.
A simple way to minimize the number of img nodes handled and modified (except for screen positioning) is to use an LRU (Least Recently Used) cache.
Basically you keep a cache of last say 100 image nodes (they must be enough to cover at least one screen) by using a dictionary mapping the src url to a node object and also keeping them all in a doubly-linked list.
When a tile is required you first check in the cache, and if it's already there just move it to the front of LRU list and move the img coordinates, otherwise create a new node and set the source or, if you already hit the cache limit, reuse the last node in the doubly-linked list instead. In code:
function setTile(x, y, src) {
var t = cache[src];
if (!t) {
if (cache_count == MAXCACHE) {
t = lru_last;
t.prev.next = null;
lru_last = t.prev;
t.prev = t.next = null;
delete cache[t.src]
t.src = src;
t.img.src = src;
cache[t.src] = t;
} else {
t = { prev: null,
next: null,
img: document.createElement("img") };
t.src = src;
t.img.src = src;
t.img.className = "tile";
scr.appendChild(t.img);
cache[t.src] = t;
cache_count += 1;
}
} else {
if (t.prev) t.prev.next = t.next; else lru_first = t.next;
if (t.next) t.next.prev = t.prev; else lru_last = t.prev;
}
t.prev = null; t.next = lru_first;
if (t.next) t.next.prev = t; else lru_last = t;
lru_first = t;
t.img.style.left = x + "px";
t.img.style.top = y + "px";
scr.appendChild(t.img);
}
I'm also always appending the requested tile to the container so that it goes in front of all other existing tiles; this way I don't need to remove old tiles and they're simply left behind.
To update the screen I just iterate over all the tiles I need and request them:
function setView(x0, y0) {
var w = scr.offsetWidth;
var h = scr.offsetHeight;
var iy0 = y0 >> 7;
var ix0 = x0 >> 7;
for (var y=iy0; y*128 < y0+h; y++) {
for (var x=ix0; x*128 < x0+w; x++) {
setTile(x*128-x0, y*128-y0, "tile_" + y + "_" + x + ".jpg");
}
}
}
most of the time the setTile request will just update the x and y coordinates of an existing img tag, without changing anything else. At the same time no more than MAXCACHE image nodes will be present on the screen.
You can see a full working example in
http://raksy.dyndns.org/tiles/tiles.html

Categories

Resources