storing base64 in localstorage - javascript

Well i have a function in javascript:
function store_data(){
var img=document.createElement("img");
/*var img=new Image();
img.onload = function() {
context.drawImage(img, 0, 0);
};*/
img.src= URL; //js global var
var height=parseInt(img.naturalHeight,10);
var width=parseInt(img.naturalWidth,10);
var canvas = document.getElementById('myCanvas');
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
var context = canvas.getContext('2d');
context.drawImage(img,0,0);
canvas.style.width="100%";
var data=(canvas.toDataURL("image/png"));
localStorage.setItem("data", data);
}
The first time when is called store a string like "data;" in localStorage is incomplete the image is like a "data64;aotehtahotetav...". But when i call for second time the data is stored fine. Why happens that?
Perhaps i should load the image in a img of the dom loaded? The image is stored for using in draw late.

Like Michael has already mentioned your code is saving the image's data to localStorage before it has completely downloaded. The second time the image already exists in cache.
Maybe try loading the image onto the canvas when the onload event fires like so
function store_data() {
var img = new Image();
img.src = URL; //js global var
img.onload = function( ) {
var canvas = document.getElementById( 'myCanvas' );
canvas.setAttribute( "width", img.width );
canvas.setAttribute( "height", img.height );
var context = canvas.getContext( '2d' );
context.drawImage( img, 0, 0 );
canvas.style.width = "100%";
var data = canvas.toDataURL("image/png");
localStorage.setItem( "data", data );
}
}

If you don't do your data storage in img.onload, then you cannot be certain that the image's data has been entirely downloaded when you're storing it in local storage, and you will get inconsistent data lengths.

Related

How to draw an image in a canvas

So I was trying to draw animgin a canvas I tried everything but in the console it says img is not a property or something like that I don't remember so can anyone help?
Here's the js
function setupcanvas() {
var canvas = document.querySelector('canvas')
var c = canvas.getContext("2d")
c.beginPath();
var img = new image()
img.src = "flappy_bird_bird.png"
img.onload = function(){
c.drawImage(img, 100, 100)
}
}
Edit
Thx to mhkanfer "sorry if the name is wrong" I fixed it
You were mostly right, though their are a couple of things:
Make sure Image() is capitalized
Make sure your image src file actually exists in that directory
And make sure your canvas has a width and height, if you haven't specified that anywhere, you canvas wont be shown
If you were to revise this, it would look something like:
function setupcanvas() {
var canvas = document.querySelector('canvas')
var c = canvas.getContext("2d")
canvas.width = canvas.height = 200;
var img = new Image()
img.src = "example.png"
img.onload = function(){
c.drawImage(img, 0, 0)
}
}

HTML5 camera image to local storage

my mobile app first uses the camera element of html5 and then takes a picture. The picture then shows on a seperate div. I'm having problems naming the image & then saving both the image and the caption to localstorage. Are my attempts futile, or is there a way to do this?
Thank you for any help or guidance offered.
To save an image in localstorage you need to convert it to dataURL string. You can do this via the canvas element as shown below.
When you want to retrieve the image from localstorage and display it you can simply set the src attrib of an image element to the dataURL string.
// convert image to localstorage friendly data URL string
function getImageDataURL(img) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL('image/png');
return dataURL;
}
var image = new Image();
image.onload = function() {
var dataURL = getImageDataURL(image);
document.body.innerHTML = dataURL;
image.src = dataURL;
document.body.appendChild(image);
};
image.crossOrigin = 'anonymous';
image.src = '//placekitten.com/g/120/120';

why save value come "null" (trying to save image in encode64)?

I am trying to save image in encoded64 and than get the value of image from local storage .But I am getting null value why ?
here is my fiddle:
http://jsfiddle.net/sAH8w/7/
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
try {
localStorage.setItem("elephant", dataURL);
}
catch (e) {
alert('error')
console.log("Storage failed: " + e);
}
//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
This minor change fix the issue:
$('#save').click(function(){
var image = new Image();
image.src = "https://dl.dropboxusercontent.com/s/t2ywui846zp58ye/plus_minus_icons.png?m=";
getBase64Image(image);
})
Working fiddle: http://jsfiddle.net/robertrozas/sAH8w/15/
Update(get button): http://jsfiddle.net/robertrozas/sAH8w/17/

Chrome cannot get the width and height from an image created by JavaScript

My web application has many image presentation features, and most of time we need to resize them. I attempted to get its real width and height values by the following fragment code:
var image = new Image();
image.src = IMAGE_URL;
var width = image.width;
var height = image.height;
The above code runs no problem on browsers like Firefox and IE 10, but it returns 0 on Chrome. I guess Chrome doesn't support this.
Can anybody gives me guidance on this?
you need to get width and height after the image loads and understands what its made of.
try:
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
}
image.src = IMAGE_URL;
hope that helps
Try this
img = new Image();
img.onload = function() {
width = this.width;
height = this.height;
};
Onload help you to get width and height.
You need to wait for the load event, otherwise the dimensions of the image won't be known.
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
// These values will now be correct.
};
image.src = IMAGE_URL;

How do I handle many images in my HTML5 canvas?

I'm very new to Html5 canvas and Javascript. I'm trying this :
function animate() {
var image1 = new Image();
image.src = /path
var image2 = new Image();
image2.src = /path
for(;;)
{
//change value of x and y so that it looks like moving
context.beginPath();
context.drawImage(<image>, x, y );
context.closePath();
context.fill();
}
}
EDIT:
And I call the animate function each 33ms :
if (playAnimation) {
// Run the animation loop again in 33 milliseconds
setTimeout(animate, 33);
};
If I follow the answer given here, I get the image struck and its not moving any further.
Update: Based on new information in the question, your problem (restated) is that you want to either
wait for all images to load first, and then start animating with them, or
start animating and only use an image if it is available.
Both are described below.
1. Loading many images and proceeding only when they are finished
With this technique we load all images immediately and when the last has loaded we run a custom callback.
Demo: http://jsfiddle.net/3MPrT/1/
// Load images and run the whenLoaded callback when all have loaded;
// The callback is passed an array of loaded Image objects.
function loadImages(paths,whenLoaded){
var imgs=[];
paths.forEach(function(path){
var img = new Image;
img.onload = function(){
imgs.push(img);
if (imgs.length==paths.length) whenLoaded(imgs);
}
img.src = path;
});
}
var imagePaths = [...]; // array of strings
loadImages(imagePaths,function(loadedImages){
setInterval(function(){ animateInCircle(loadedImages) }, 30);
});
2. Keeping track of all images loaded so far
With this technique we start animating immediately, but only draw images once they are loaded. Our circle dynamically changes dimension based on how many images are loaded so far.
Demo: http://jsfiddle.net/3MPrT/2/
var imagePaths = [...]; // array of strings
var loadedImages = []; // array of Image objects loaded so far
imagePaths.forEach(function(path){
// When an image has loaded, add it to the array of loaded images
var img = new Image;
img.onload = function(){ loadedImages.push(img); }
img.src = path;
});
setInterval(function(){
// Only animate the images loaded so far
animateInCircle(loadedImages);
}, 100);
And, if you wanted the images to rotate in a circle instead of just move in a circle:
Rotating images: http://jsfiddle.net/3MPrT/7/
ctx.save();
ctx.translate(cx,cy); // Center of circle
ctx.rotate( (angleOffset+(new Date)/3000) % Math.TAU );
ctx.translate(radius-img.width/2,-img.height/2);
ctx.drawImage(img,0,0);
ctx.restore();
Original answer follows.
In general, you must wait for each image loading to complete:
function animate(){
var img1 = new Image;
img1.onload = function(){
context.drawImage(img1,x1,y1);
};
img1.src = "/path";
var img2 = new Image;
img2.onload = function(){
context.drawImage(img2,x2,y2);
};
img2.src = "/path";
}
You may want to make this code more DRY by using an object:
var imgLocs = {
"/path1" : { x:17, y:42 },
"/path2" : { x:99, y:131 },
// as many as you want
};
function animate(){
for (var path in imgLocs){
(function(imgPath){
var xy = imgLocs[imgPath];
var img = new Image;
img.onload = function(){
context.drawImage( img, xy.x, xy.y );
}
img.src = imgPath;
})(path);
}
}

Categories