callback returning true/false - javascript

I'm wondering what I am missing here I have a code that checks if the image is transparent based on canvas.
function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}
When I'm doing it this way:
function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}
function callback(success, npc) {
if (success) {
console.log("Not trasparent");
} else {
console.log("Trasparent");
}
}
Trasparent(npc.icon, npc, callback);
It works just fine, but when I'm trying to make this function above like this:
function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
return false;
} else {
return true;
}
};
}
if(Transparent(npc.icon, npc)){
console.log("Not transparent");
} else {
console.log("Trasparent");
}
It doesn't work...
Even tho in this example which i wrote it works fine:
function check(a, b) {
var result = a + b;
if (result <= 10) {
return (false);
} else {
return (true);
}
}
function test() {
if (check(5, 4)) {
console.log(">10");
} else {
console.log("<10")
}
}
test();
What i am missing?

The return-statements are not belonging to the function Transparent!
You are creating a different function here which returns true or false when it is called, but it is not executed right away and it's return-value is not returned in your function Transparent.
What you have is essentially this snippet:
function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = function() {
// function body totally unrelated to the Transparent-function
// and not executed and not returning anything right now
};
return undefined;
}
(these are not actually the same since fat arrow functions capture this, see What does "this" refer to in arrow functions in ES6?)
Your solution with the callback is the way to go.

your code is async. you cant return true or false. you need to return a callback thats why your if doesn't work
function Trasparent(url, npc,cb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
cb(false);
} else {
cb(true);
}
};
}
Transparent(npc.icon, npc,function(result){
if(result)
console.log("Not transparent");
} else {
console.log("Trasparent");
}
})
)

Related

problem with clearRect and element rendering

the question may seem simple, but I can not understand what is my mistake.
I draw images on my canvas, everything is fine, but at the moment when I add clearRect, the elements are completely removed from the canvas without restoring them. Although the cleanup cycle should happen before the rendering
what's my mistake? everything seems to be simple, but I'm stuck with it for a very long time
App main game class
Game class - responsible for rendering to the canvas and clearing it
player - responsible for the logic of the player's behavior
animation - requestanimationframe is called in this function, on the function passed to it
class App {
constructor() {
this.player = new Player("Player 1", 0, 102);
this.game = new Game();
this.game.CreateCanvas();
window.addEventListener('keyup', () => this.player.UpKey());
window.addEventListener('keydown', (event)=> this.player.HandlerKeyPress(event));
new Animation(this.Display.bind(this));
}
Display() {
this.game.ClearCanvas();
this.SetLevel();
}
SetLevel() {
this.game.LoadSprite(assets.mario, [...player_assets.mario.small.standing_right, ...this.player.GetPosition(), 16, 16]);
this.StaticObject();
}
StaticObject () {
for(let i = 0; i < 32; i++){
this.game.LoadSprite(assets.block, [...lvl_1.block.ground.size, i* 16, 134, 16,16]);
this.game.LoadSprite(assets.block, [...lvl_1.block.ground.size, i* 16, 118, 16,16]);
}
}
}
new App();
export default class Game {
CreateCanvas () {
this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
document.body.appendChild(this.canvas);
}
ClearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
SetBackgroundColor (color) {
this.ctx.fillStyle = color;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
LoadSprite (src, position) {
const _image = new Image();
_image.src = src;
_image.onload = () => {
this.ctx.drawImage(_image, ...position, true);
}
}
}
export default class LoopAnimation {
constructor(display) {
this.display = display;
this.Animation = this.Animation.bind(this);
this.Animation();
}
Animation() {
requestAnimationFrame(this.Animation);
this.display();
}
}
My suspicion is it's related to cache and event onload not firing. image.onload event and browser cache
suggests to set the onload property before the src.
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";
If you want to reuse loaded images, then store them in an array. Then reuse the image from there. See for example:
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 450;
canvas.height = 250;
const ctx = canvas.getContext("2d");
const assets = [
"https://picsum.photos/id/237/150",
"https://picsum.photos/id/235/150",
"https://picsum.photos/id/232/150",
];
const assetsLoaded = assets.map(url =>
new Promise(resolve => {
const img = new Image();
img.onload = e => resolve(img);
img.src = url;
})
);
Promise
.all(assetsLoaded)
.then(images => {
(function gameLoop() {
requestAnimationFrame(gameLoop);
ctx.clearRect(0, 0, canvas.width, canvas.height);
images.forEach((e, i) =>
ctx.drawImage(
e,
i * 150 + Math.cos(Date.now() * 0.003 + i) * 20, // x
Math.sin(Date.now() * 0.005 + i) * 50 + 50 // y
)
);
})();
})
.catch(err => console.error(err))
;
// from https://stackoverflow.com/a/61337279/3807365
Specifically for your question, you can declare a global object var cache={} where its keys are the src of images to load. so, for example:
var cache = {};
LoadSprite(src, position) {
if (cache[src]) {
this.ctx.drawImage(cache[src], ...position, true);
return;
}
const _image = new Image();
_image.src = src;
_image.onload = () => {
cache[src] = _image;
this.ctx.drawImage(_image, ...position, true);
}
}

How to set filename while converting canvas to blob?

I want to upload cropped image to server. For this I am using jQuery Jcrop lib in this canvas image cropped then convert to blob that is working perfectly , but the problem is that file name on server is just blob without any extension or undefined type.
When I am using this in img Sec on web page it's working perfectly.
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob);
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>
Thanks #Zigri2612 for Solution
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob,"image.png");
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>

JCrop: Manipulate image from external URL

I need to rotate/scale/flip/crop an image on an HTML page.
I'm using JCrop.js for image manipulation on client side. I'm able to do this successfully with a file selector, where the user selects an image file on their local computer. My requirement is to do the same, but for an image loaded from another URL (without selecting a local image).
Need help on the next step.
Here is the complete code that works well with local file selection:
HTML:
<img scr="externalURL" id="imgMain" alt=""/>
<input type="button" id="cropbutton" value="Crop" />
<input type="button" id="rotatebutton" value="Rotate" />
<input type="button" id="hflipbutton" value="Flip Horizontal" />
<input type="button" id="vflipbutton" value="Flip Vertical" />
JS:
var cropWidth = 800;
var cropHeight = 800;
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$(document).ready(function () {
$("#file").change(function () {
loadImage(this);
});
$("#btnCrop").click(function () {
SaveData();
});
});
function SaveData() {
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(canvas.toDataURL('image/jpeg'));
formData.append("cropped_image[]", blob, "CroppedImage.jpeg");
$.ajax({
url: urlToSendData
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
alert("Image cropped!");
},
error: function (data) {
alert('There was an error');
}
});
}
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function (e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
applyCrop();
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
boxWidth: crop_max_width,
boxHeight: crop_max_height,
allowResize: false,
allowSelect: false,
setSelect: [0, 0, cropWidth, cropHeight],
aspectRatio: 1
}, function () {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width - 10, canvas.height - 10);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#scalebutton").click(function (e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function (e) {
applyRotate();
});
$("#hflipbutton").click(function (e) {
applyHflip();
});
$("#vflipbutton").click(function (e) {
applyVflip();
});
Looks like loadImage reads the file and sets the image global.
As there is now already an image on the page, we should be able to skip this step.
So we can probably just set the image in ready like this:
$(document).ready(function () {
// (this code replaces the file selecting)
image = $("#imgMain"); // set image from the page
canvas = null; // this was done in loadImage
applyCrop(); // this was called from loadImage
// (this code is the same as before)
$("#btnCrop").click(function () {
SaveData();
});
});

Loop: images land on the last field only

I have a little problem with a loop. I am building a little tool, where a user must upload 12 images. The images are cropped in rectangles and placed on buttons. I am almost ready, but somehow the loop doesn't work well. All images land on the last button. Maybe something wrong in the loop here?
JS/JQuery:
for (var i = 0; i < 12; i++) {
var j=i+1;
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.src = e.target.result;
img.onload = function () {
var getimage= '#getimage'+j;
// CREATE A CANVAS ELEMENT AND ASSIGN THE IMAGES TO IT.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height)
var posh, posw;
var factheight=img.height;
var factwidth=img.width;
if(factwidth<factheight){
canvas.width = img.width;
canvas.height= img.width;
posh=(img.height-img.width)/2;
posw=0;
}
else if(factheight<factwidth){
canvas.height = img.height;
canvas.width = img.height;
posh=0;
posw=(img.width-img.height)/2;
}
else{
canvas.width = img.width;
canvas.height= img.height;
posh=0;
posw=0;
}
ctx.drawImage(img, posw, posh, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
var cropped=canvas.toDataURL("image/png");
$(getimage).attr("src",cropped); // SHOW THE IMAGES OF THE BROWSER.
}
}
reader.readAsDataURL($('.multiupload')[0].files[i]);
}
Here is also a link to the JSFiddle. Appreciate your help, since I don't know exactly how reader.readAsDataURL($('.multiupload')[0].files[i]); and target.result works
I'm guessing that your loop has finished before any of the images are fully loaded so j will be 11 before its used to find the relevant button. Try changing
img.onload = function () { .... }
to
img.onload = myFunction(id)
Then move everything out of the inline function into its own function with an input parameter. Then pass j as the id param.
I've done an example for you. As I answered in comments
var reader = new FileReader();
reader.onload = (function(j){return function (e) {
var img = new Image();
...
https://jsfiddle.net/ykze3f9r/
The main issue with the code was the j variable. It was always set to the last number because of the way for loops work. You have to instead bind that number. I broke up into separate functions to make it easier to read. Here's the working JSFiddler: https://jsfiddle.net/eh6pr7ee/2/
Processes the image...
var processImg = function( img, imgNum ) {
var getimage= '#getimage' + imgNum;
// CREATE A CANVAS ELEMENT AND ASSIGN THE IMAGES TO IT.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height)
var posh, posw;
var factheight = img.height;
var factwidth = img.width;
if (factwidth < factheight) {
canvas.width = img.width;
canvas.height = img.width;
posh = (img.height-img.width)/2;
posw = 0;
}
else if (factheight < factwidth) {
canvas.height = img.height;
canvas.width = img.height;
posh = 0;
posw = (img.width-img.height)/2;
}
else {
canvas.width = img.width;
canvas.height= img.height;
posh = 0;
posw = 0;
}
ctx.drawImage(img, posw, posh, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
var cropped = canvas.toDataURL("image/png");
$(getimage).attr("src",cropped); // SHOW THE IMAGES OF THE BROWSER.
};
Creates image and sets source...
var setImage = function( imgNum, e ) {
var img = new Image();
img.src = e.target.result;
img.onload = processImg.bind( this, img, imgNum );
};
Create a handler function for image uploads...
var handleImageUploads = function() {
if (parseInt($(this).get(0).files.length) > 12 || parseInt($(this).get(0).files.length) < 12) {
alert("Please upload 12 photos");
}
else {
//loop for each file selected for uploaded.
for (var i = 0; i < 12; i++) {
var reader = new FileReader();
reader.onload = setImage.bind( this, i+1 );
reader.readAsDataURL($('.multiupload')[0].files[i]);
} // for
console.log("done");
$('body').removeClass("loading");
}; // else
}
Binds the handler function.
$('.multiupload').on("change", handleImageUploads);

Bad performance applying blur with StackBlur for animation with fade

I have a canvas that does a transition with many images applying a alpha for the fade. The problem is that for each frame apply the blur and that do very slow the animation.
If before apply the transition, do a copy of canva and apply the blur, and after use this canvas for draw in the other canvas, the animation fade no work.
The code is the next:
function animateFade()
if (fadePct > 100) {
return;
}
requestAnimationFrame(animateFade);
draw(imgs[fadeInIndex], fadePct / 100);
draw(imgs[fadeOutIndex], (1 - fadePct / 100));
fadePct++;
}
function draw(image, opacity) {
ctx.save();
ctx.globalAlpha = opacity;
ctx.drawImage(image, 0, 0);
StackBlur.canvasRGB(canvas, 0, 0, canvas.width, canvas.height, 50);
ctx.restore();
}
imageURLs = []; // put the paths to your images here
imagesOK = 0;
imgs = [];
var items = $('.carrousel .post');
for (var i = 0; i < items.length; i++) {
image = items.eq(i).find("img").attr('src');
imageURLs.push(image);
}
for (var i = 0; i < imageURLs.length; i++) {
img = new Image();
imgs.push(img);
img.onload = function () {
imagesOK++;
if (imagesOK >= imageURLs.length) {
ctx.drawImage(imgs[0], 0, 0);
var ratio = 1;
ratio = $('#best_game').width() / img.width;
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(imgs[0], 0, 0, canvas.width, canvas.height);
StackBlur.canvasRGB(canvas, 0, 0, canvas.width, canvas.height, 50);
}
};
img.onerror = function () {
alert("image load failed");
}
img.crossOrigin = "anonymous";
img.src = imageURLs[i];
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
});

Categories