How to download pdf in nuxt project? - javascript

<div style="height: 0;position: fixed; left: 50%; top: 0; transform: translateX(-50%);
z-index: -1;overflow: hidden">
<ticket-pdf v-if="pdfData" :pdfData="pdfData" :downloadBtn="downloadBtn" #download="downloadBtn = $event" /> </div>
In my nuxt project, i need to download pdf file in my main componet .When user clicked download button it will be downloaded directlty without previewing pdf component. So i hide my ticket-pdf component inside my main component . This way works in localhost but when i published my project to test area it does not work. It download only 1 empty page. and i face with this mistake.
Failed to load resource: the server responded with a status of 500 ()
If i open my pdf file in a other page and i can preview and download it also. But i need to doownload it without routing anywhere and directly in my main component
printPDF() {
const html2canvasOptions = {
allowTaint: true,
removeContainer: true,
imageTimeout: 15000,
logging: true,
useCORS: true,
scrollX: 0,
scrollY: 0,
scale: 2,
};
// Initialize the PDF.
let pdf = new jsPDF('p', 'in', [8.5, 11], false);
let totalPage = 0
//i have many pages and countof pages changes . It depends. so firstly i calculate page count and create pdf.
let pageCount = document.querySelectorAll('[id^=contentPrint]').length
for (let i = 0; i < pageCount; i++) {
const contentPrint = document.getElementById('contentPrint-' + i);
html2canvas(contentPrint, html2canvasOptions)
.then((canvas) => {
const image = {type: 'jpeg', quality: 1};
const margin = [0.5, 0.5];
let imgWidth = 8.5;
let pageHeight = 11;
let innerPageWidth = imgWidth - margin[0] * 2;
let innerPageHeight = pageHeight - margin[1] * 2;
// Calculate the number of pages.
let pxFullHeight = canvas.height;
let pxPageHeight = Math.floor(canvas.width * (pageHeight / imgWidth));
let nPages = Math.ceil(pxFullHeight / pxPageHeight);
totalPage += nPages
// Define pageHeight separately so it can be trimmed on the final page.
pageHeight = innerPageHeight;
// Create a one-page canvas to split up the full image.
let pageCanvas = document.createElement('canvas');
let pageCtx = pageCanvas.getContext('2d');
pageCanvas.width = canvas.width;
pageCanvas.height = pxPageHeight;
for (let page = 0; page <= nPages; page++) {
// Trim the final page to reduce file size.
if (page === nPages - 1 && pxFullHeight % pxPageHeight !== 0) {
pageCanvas.height = pxFullHeight % pxPageHeight;
pageHeight = (pageCanvas.height * innerPageWidth) / pageCanvas.width;
}
// Display the page.
let w = pageCanvas.width;
let h = pageCanvas.height;
pageCtx.fillStyle = 'white';
pageCtx.fillRect(0, 0, w, h);
pageCtx.drawImage(canvas, 0, page * pxPageHeight, w, h, 0, 0, w, h);
// Add the page to the PDF.
if (page > 0) pdf.addPage();
let imgData = pageCanvas.toDataURL('image/' + image.type, image.quality);
pdf.addImage(imgData, image.type, margin[1], margin[0], innerPageWidth, pageHeight);
}
});
}
setTimeout(() => {
// pdf.deletePage(totalPage + 1)
pdf.save("e-ticket" + '.pdf')
}, 3000)
setTimeout(() => {
this.$emit("download", this.download);
}, 4000)
},
This is how i create pdf area. When user clicked download button i create pdf and download it thanks to my props.

printPDF() {
window.scrollTo(0, 0);
// Initialize the PDF.
let pdf = new jsPDF('p', 'in', [8.5, 11], false);
let totalPage = 0
let counter = 0
let myArray = []
let pageCount = document.querySelectorAll('[id^=contentPrint]').length
for (let i = 0; i < pageCount; i++) {
myArray.push('contentPrint-' + i)
}
for (let i = 0; i < pageCount; i++) {
const contentPrint = document.getElementById('contentPrint-' + i);
html2canvas(contentPrint, {
scale: 2, useCORS: true, allowTaint: true, scrollY: 0
}).then((canvas) => {
.................
........
.....
counter = counter + 1;
callBack();
})
}
const callBack = () => {
if (myArray.length === counter) {
pdf.save("filename" + '.pdf')
this.$emit("download", this.download);
}
}
},
the problem was about my settimeout function . ın there ı would call pdf.save before pdf created and sure every browser works in different speed. so if we use callback function after all process done , then we can obtain our pdf rpint

You could maybe try to simply put
<a href="/your_file.csv" download>
by putting your_file.csv into the static directory.
Not sure if it can be enough in your case, sorry if it's not.

Related

Blurred pdf with pdf.js library

I'm using pdf.js library to render my pdf file on canvas.
First I was searching a solution for rendering pdf with the size of canvas parent element.
I've found it and it works fine.
Then I solve the problem of rendering ALL pages at once.
Finally, my code now looks this way:
pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;
class PdfLoader {
currPage = 1;
numPages = -1;
doc = null;
constructor($container) {
this.$container = $container;
}
load(path) {
// reset when using more than once
this.currPage = 1;
this.promise = new Promise(resolve => this.promiseResolve = resolve);
this.$container.innerHTML = "";
pdfjsLib.getDocument(path).promise.then(pdf => {
this.doc = pdf;
this.numPages = pdf.numPages;
pdf.getPage(1).then(this._handlePage.bind(this));
});
return this;
}
_handlePage(page) {
let viewport = page.getViewport({scale: 1});
const scale = this.$container.clientWidth/viewport.width;
// const outputScale = window.devicePixelRatio || 1;
const outputScale = 1;
viewport = page.getViewport({scale});
const cnv = document.createElement("canvas");
const ctx = cnv.getContext("2d");
const width = Math.floor(viewport.width);
const height = Math.floor(viewport.height);
cnv.width = Math.floor(width * outputScale);
cnv.height = Math.floor(height * outputScale);
cnv.style.width = `${width}px`;
cnv.style.height = `${height}px`;
const transform = (outputScale !== 1) ? [outputScale, 0, 0, outputScale, 0, 0] : null;
page.render({
canvasContext: ctx,
transform: transform,
viewport: viewport,
});
this.$container.appendChild(cnv);
this.currPage++;
if (this.doc !== null && this.currPage <= this.numPages) {
this.doc.getPage(this.currPage).then(this._handlePage.bind(this));
} else {
this.promiseResolve();
}
}
}
const $pages = document.getElementById("pages");
const pdfLoader = new PdfLoader($pages);
pdfLoader.load("extendedReport.pdf").promise
.then(initReport);
let arrow = null;
function initReport() {
// my other stuff
}
And now my problem is that when viewing rendered pdf it looks like its quality is very low and text is blurred so the document is unreadable on mobile devices. I tried to change passed scale like they say on the internet, but that's not it. Could you help me, plz? What am I missing?

User Image Upload in React without quality Loss

I'm working at a company where a File Uploader was already implemented, but for some reason we are saving the photo and its quality is greatly reduced. Basically, I want to know what the easiest way is to implement a component where a user can upload a profile photo or logo, and we can save it without losing quality. I also want to be able to resize it to various dimensions without losing quality. I don't necessarily need a cropper either, I want the user to be able to upload the photo and we display the full image, just resized without quality loss. Techstack is using JS and React.
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.fileRef = createRef();
this.imgCanvas = createRef();
this.previousMoveX = 0;
this.previousMoveY = 0;
this.state = {
showUploadModal: false || props.showUploadModal,
img: '',
imgControl: false,
imgControlZoom: 0,
imgControlMove: false,
imgControlX: 0,
imgControlY: 0,
};
this.onImgRead = this.onImgRead.bind(this);
this.onChangeImage = this.onChangeImage.bind(this);
this.onChangeZoom = this.onChangeZoom.bind(this);
this.onStartMove = this.onStartMove.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
}
componentDidUpdate() {
const { img, imgControlZoom, imgControlX, imgControlY } = this.state;
if (img === '') return;
let canvas = this.imgCanvas.current;
if (canvas === null) return;
let ctx = canvas.getContext('2d');
let imgNode = new Image();
imgNode.onload = () => {
const s = parseInt(
Math.min(imgNode.width, imgNode.height) / ((imgControlZoom + 100) / 100)
);
const k = canvas.width / s;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(
imgNode,
0,
0,
imgNode.width,
imgNode.height,
imgControlX + (s - imgNode.width) * 0.5 * k,
imgControlY + (s - imgNode.height) * 0.5 * k,
imgNode.width * k,
imgNode.height * k
);
};
imgNode.src = img;
}
onChangeImage(e) {
const input = e.target;
const { files } = e.target;
if (files === 0) return;
const file = files[0];
if (file.size > FILE_SIZE) {
toast.error(FILE_SIZE_VALIDATION);
return;
}
const fileReader = new FileReader();
fileReader.onload = ev => {
input.value = '';
this.onImgRead(ev.target.result);
};
fileReader.readAsDataURL(file, 'UTF-8');
}
This has nothing to do with React, and is not usually implemented on the client with JS, unless you are using NodeJS on the server. This feature is usually implemented on the server. Such as http_image_filter_module module of nginx.
For lossy image formats (such as jpeg), any change will again lose the quality of the image, although this loss is usually very small. If you really need to have a very high quality of the image, you need to convert them to lossless image formats (such as png) on the server first.

Firefox extension not able to select all images may be due to Canvas fuction getImageData()

In the below code I have imported my machine learning model through function model_startup(). model_startup() is working fine. But after that, I am getting into function blockk(), through this function I am trying to select all images on website by document.getElementsByTagName('img') and do prediction through that image with the help of an imported model. But my problem is that my second function is not selecting all images on website and selecting only some number of starting images and after prediction on that some number of images it get stopped.
I am new to javascript and trying to implement it as a firefox extension. Please help me in this problem
console.log('STARTING UP')
const MODEL_PATH = 'mdl/model.json'
const IMAGE_SIZE = 64;
let model;
async function model_startup()
{
console.log('Launching TF.js!');
tf.ENV.set('WEBGL_PACK',false);
await tf.ready();
console.log('TensorflowJS backend is: '+tf.getBackend());
let url = browser.runtime.getURL(MODEL_PATH);
console.log('Loading model... '+url);
try
{
model = await tf.loadLayersModel(url);
}
catch(e)
{
console.log('Failed to load model! '+e);
}
console.log('Model: ' + model);
console.log('Warming up...');
let dummy_data = tf.zeros([1, IMAGE_SIZE, IMAGE_SIZE, 3]);
// dummy_data.print();
let warmup_result = model.predict(dummy_data);
console.log("finding type : $$$$$$$$ " + typeof warmup_result)
warmup_result.print();
warmup_result.dispose();
console.log('Ready to go!');
// blockk();
};
model_startup().then(blockk);
function blockk() {
const x = document.getElementsByTagName('img');
console.log("wn ############################## " + x.length);
let inferenceCanvas = document.createElement('canvas');
inferenceCanvas.width = 64;
inferenceCanvas.height = 64;
let inferenceCtx = inferenceCanvas.getContext('2d', { alpha: false});
inferenceCtx.imageSmoothingEnabled = true;
for(var i = 0; i < x.length; i++)
{
console.log('pixel kmvsl lsvn');
let img = x[i];
inferenceCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, 64, 64);
const rightSizeImageData = inferenceCtx.getImageData(0, 0, 64, 64); //write promise. It may work.
const rightSizeImageDataTF = tf.browser.fromPixels(rightSizeImageData);
const floatImg = rightSizeImageDataTF.toFloat();
console.log('predicting...');
let scaled = floatImg.div(tf.scalar(255));
let batched = tf.stack([scaled]);
let result = model.predict(batched);
const val = result.dataSync()[0];
console.log(val);
if (val > 0.4)
{
console.log("blocking" + i);
let h = img.height
let w = img.width
pth = img.src
x[i].setAttribute("src", "https://indianonlineseller.com/wp-content/uploads/2017/05/blocked-listing.png");
// x[i].setAttribute("onclick", ` this.src = '${pth}' `);
x[i].setAttribute("data-src", "https://indianonlineseller.com/wp-content/uploads/2017/05/blocked-listing.png");
x[i].height = h;
x[i].width = w;
console.log('blocked');
}
console.log("co ########################### " + x.length)
}
};
The line in my code which is causing problem is
const rightSizeImageData = inferenceCtx.getImageData(0, 0, 64, 64);
If I remove this code and other code related to this line and I run it then my code is able to select all the images on webpage. Can you tell me why this may be happening?

Ionic 3 - remove images from an ion-slides with help of .getActiveIndex()

I have added images from gallery/camera to an ion-slider view.I have an action sheet which gives me an option to add or remove the images from the slider view.Adding is working fine as i am adding that image to array and providing that updated array to the slider.
But for removing an image i need to get the index of the image that is active on the slider and after that i need to remove it.
I m not able to get the active index using this code :
onSlideChanged() {
try{
let currentIndex = this.slides.getActiveIndex();
console.log("Current index is", currentIndex);
}catch(e){
console.log("not able to get the active index");
} }
this also goes into the catch part.
Then i m removing the first element from the array and updating the array for slider.The array size is reduced when i press the delete button from action sheet but all the images in the slider disappears leaving a blank space.
<div *ngIf="field.value" (click)="takePicture(field.name)">
<ion-slides pager="true" style="max-height:500px" (ionSlideDidChange)="onSlideChanged()">
<ion-slide *ngFor="let c of field.value">
<img class="image-attach" [src]="c" draggable="true">
</ion-slide>
</ion-slides>
</div>
<canvas #latlon style="display:none"></canvas>
</div>
code for setting images to the slider
removePicture(name) {
for (let i = 0; i < this.formType.template.secs.length; i++) {
for (let d = 0; d < this.formType.template.secs[i].fields.length; d++) {
if (this.formType.template.secs[i].fields[d].name == name) {
if(this.formType.template.secs[i].fields[d].value.length>1)
{
this.formType.template.secs[i].fields[d].value.splice(this.currentIndex,1);
this.attachedImagesArray.splice(this.currentIndex,1);
console.log(this.formType.template.secs[i].fields[d].value.length);
var arr = this.formType.template.secs[i].fields[d].value;
console.log("^^^^^^^",arr);
this.formType.template.secs[i].fields[d].value = this.formType.template.secs[i].fields[d].value;
}
else{
console.log("*********",this.formType.template.secs[i].fields[d].value);
this.formType.template.secs[i].fields[d].value = "";
}
}
}
}
};
this is the code i m using for removing the images from slider.
I m new to ionic so don't know why this is happening, i googled for it but nothing worked for me.
for putting the images to the slides i m using the following code :
selecPicture(name) {
this.camera.getPicture({
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
targetHeight: 500,
targetWidth: 500,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}).then((imageData) => {
//alert(imageData);
// imageData is a base64 encoded string DATA_URL FILE_URI 'lat: '+lat+', lon: '+lon,
let base64Image = "data:image/jpeg;base64," + imageData;
this.geolocation.getCurrentPosition().then((resp) => {
let lat = resp.coords.latitude;
let lon = resp.coords.longitude;
this.lat = lat;
this.lon = lon;
let d = new Date();
let draftSavedTime = d.toString().substr(4, 11);
let canvas = this.canvasRef.nativeElement;
let context = canvas.getContext('2d');
console.log(context);
console.log("hello");
let newImg = new Image();
newImg.src = imageData;
newImg.onload = () => {
canvas.setAttribute("width", newImg.height);
canvas.setAttribute("height", newImg.width);
// context.drawImage(newImg, 0, 0);
context.drawImage(newImg, 0, 0, newImg.width, newImg.height);
// context.font = "15px impact";
context.font = "bold 13px Arial";
// context.textAlign = 'center';
context.fillStyle = 'red';
context.fillText(draftSavedTime, 20, 20);
// context.fillText('Lat: '+lat+' Lon: '+lon, canvas.width / 2, canvas.height * 0.9);
context.fillText('Lat: ' + lat, canvas.width * 0.1, canvas.height * 0.8);
context.fillText('Lon: ' + lon, canvas.width * 0.1, canvas.height * 0.9);
// context.fillText('Lon: '+lon, canvas.width / 2, canvas.height * 0.8);
let image = canvas.toDataURL();
this.attachedImages.push(image);
this.setValue(name, image);
};
}).catch((error) => {
console.log('Error getting location', error);
});
}, (err) => {
console.log(err);
});
}
to set the value of image in the field :
//to set the value in the field
setValue(name, data) {
console.log(this.attachedImages);
console.log(this.formType.template.secs); //3
for (let i = 0; i < this.formType.template.secs.length; i++) {
console.log(this.formType.template.secs[i].fields); //2
for (let d = 0; d < this.formType.template.secs[i].fields.length; d++) {
if (this.formType.template.secs[i].fields[d].name == name) {
this.attachedImagesArray.push({
name : this.formType.template.secs[i].fields[d].name,
image : data,
number : d
});
var group_to_values = this.attachedImagesArray.reduce(function (obj, item) {
obj[item.name] = obj[item.name] || [];
obj[item.name].push(item.image);
return obj;
}, {});
var imageGroup = Object.keys(group_to_values).map(function (key) {
return {key: key, image: group_to_values[key]};
});
var pre = document.createElement("pre");
pre.innerHTML = "imageGroup:\n\n" + JSON.stringify(imageGroup, null, 4);
document.body.appendChild(pre);
var newArr = [];
newArr.push({imageGroup});
for(var item in newArr)
{
console.log(newArr[item]);
for(var sec in newArr[item])
{
console.log(newArr[item][sec]);
}
for( var elm in newArr[item][sec])
{
console.log(newArr[item][sec][elm]);
}
for( var key in newArr[item][sec][elm])
{
this.arrNameStr = newArr[item][sec][elm].key;
console.log(newArr[item][sec][elm].image);
}
}
console.log(this.arrNameStr);
if(this.arrNameStr.includes(this.formType.template.secs[i].fields[d].name))
{
console.log(newArr[item][sec][elm].image);
console.log(this.formType.template.secs[i].fields[d].value);
this.formType.template.secs[i].fields[d].value = newArr[item][sec][elm].image;
console.log(this.formType.template.secs[i].fields[d].value);
}
}
}
}
};
First ensure that you get this event firing off and that your reference to the slides element in the template returns the Slides: (ionSlideDidChange). Do:
onSlideChanged() {
console.log(this.slides)
}
Your console should return reference to the slides element.
It is unclear how you obtain this reference based on your code, but seeing you have *ngIf directive there is a chance you are not actually able to get it since the element doesn't exist at init stage of the component.
To fix that you can pass reference to ion-slides in the ionSlidesChanged method:
<div *ngIf="field.value" (click)="takePicture(field.name)">
<ion-slides #mySlides (ionSlideDidChange)="onSlideChanged(mySlides); mySlides.update()" pager="true" style="max-height:500px">
<ion-slide *ngFor="let c of field.value">
<img class="image-attach" [src]="c" draggable="true">
</ion-slide>
</ion-slides>
</div>
Now in the actual method you should be able to get the value of currentIndex:
onSlideChanged(mySlides) {
let currentIndex = mySlides..getActiveIndex();
// here do splice or whatever manipulation you need with your data source / array
}
Let me know if this helped.
UPDATE: since there is a need to refresh slides UI after the change to the model it is good to call "update" method: (ionSlideDidChange)="onSlideChanged(mySlides); mySlides.update()".
Template is now updated with this.

How to put a gif with Canvas

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.

Categories

Resources