Restore canvas with base64 string - javascript

Whenever i first loaded the page. The image doesn't get restored but once i load the page and i hit F5. then it works. i'm not where whats wrong with my code.
// variable r contains the base64 string which is retrieved via a ajax call.
var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(myImage, 0, 0);
Ok. Instead of calling the ajax automatically when the page is loaded, i manually triggered the ajax call via a button, still i get the same result.
The base64 strings is retrieved successfully and imaged is not loaded. but when i clicked the button for a second time. the image is than loaded.

var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// wait for it to load before calling draw
myImage.onload = function() {
ctx.drawImage(myImage, 0, 0);
}

Related

create image data in javascript

I want to create a black (or white, I really don't care the "colour") 1x1px image in javascript, I tried doing it with var img = new Image(1,1) but I don't know how assigng the source of the image with img.src to be all black (I don't want to use a file, I want to be generated with JS code).
There is a way to do that?
You can also use base64 encoded data in the image.src.
var image = new Image(10, 10);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
document.body.appendChild(image);
I found it:
var image = document.createElement('canvas').getContext('2d').getImageData(0,0,1,1);
I'll let question open to know if there is another way to do it.
Sources I used:
CanvasRenderingContext2D.createImageData()
CanvasRenderingContext2D.getImageData()
Similarly you can perform the image manipulation in canvas, then pass a data URI containing a representation of the image over to the HTML image for actual rendering.
const imgWidth = 1;
const canvas = document.createElement("canvas");
canvas.width = imgWidth;
canvas.height = imgWidth;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,imgWidth,imgWidth);
const url = canvas.toDataURL();
const newImg = document.createElement("img");
newImg.src = url;
document.body.insertBefore(newImg, null);

Store local image to upload in another page [duplicate]

This question already has answers here:
How to save an image to localStorage and display it on the next page?
(8 answers)
Closed 6 years ago.
I have to make an image input that will not upload the image. The images will be used in another page where it will be edited(cropped and draw over) and then uploaded.
I don't know how to do that, do you have any ideas? I'll probably be using this plugin.
you have get the image using getElementByID. convert the image in to base64 and save in local storage
userimage = document.getElementById('imageId');
imageData = getBase64Image(userimage);
localStorage.setItem("imageData", imageData);
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
insert the script in your second page for getting the image from localstorage and set to the image src
window.onload = function() {
var getpicture = localStorage.getItem('imageData');
var image = document.createElement('img');
image.src = getpicture;
};

How to save and load HTML5 Canvas to & from localStorage?

I want the user to be able to save canvas drawings to the localStorage (using the Save button)under a custom name and then be able to load (using the load button) previous drawings from the localStorage.
First option
If you want to save just a bitmap then you can save it this way:
localStorage.setItem(canvasName, canvas.toDataURL());
and then load like this:
var dataURL = localStorage.getItem(canvasName);
var img = new Image;
img.src = dataURL;
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
I recommend to use canvas.toDataURL() instead of ctx.getImageData() because ctx.getImageData() JSON string size will be just enormous even if canvas is empty.
Second option
If you want to store canvas as lines array then you should store lines coords in some variable and save it`s json:
localStorage.setItem(canvasName, JSON.stringify(linesArray));
Then you can load lines array and redraw canvas:
var lines = JSON.parse(localStorage.getItem(canvasName));
lines.forEach(function (line) {
ctx.beginPath();
ctx.strokeStyle = line.color;
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.stroke();
});
First step will be to get image data from canvas.
var imageData = myCtxt.getImageData(0,0,WIDTH,HEIGHT);
Now store it to localStorage after stringifying it:
localStorage.setItem(savekey, JSON.stringify(idt));
To read and set the data back you can use following:
var idt = localStorage.getItem(savekey) || null;
if (idt !== null) {
var data = JSON.parse(idt);
ctx.putImageData(idt, 0, 0);
}
I have put the functions to handle the functionality in your fiddle.
Regarding localStorage you can read this and this questions.

How convert downloaded inline image into Base64 on client side

Is there any technique to convert images that have already been downloaded – inline JPEG/GIF/etc. images that occur in a webpage – into Base64 data using client-side JavaScript?
I am not talking about how to transform an image into Base64 using other means (server-side, online tools, etc.).
These are the constraints for my particular use case:
The image is on screen now, right in the page, in front of person. It has already been downloaded in a data sense.
The conversion from raw image data has to be done client-side.
The images in question are from arbitrary domains. That is, they may or may not, be of same origin domain.
The user, if needed (if helpful to solution), can give additional permissions (for example, a FF toolbar install to help skirt cross-domain and other issues). That is, code can be given special endorsement on the client side if that helps solve the issue.
The end goal is to transform all images on the page (in the DOM) into Base64 data inside of JavaScript. Put another way, every image the user can see on the page has been converted into a JavaScript variable of some sort that contains the Base64 data.
So far I see no posts that stay inside of all the above constraints.
I think this is close to what you are looking for but the only problem is that it only works for locally hosted images and HTML5 only.
function toURL(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
var test = document.getElementById("myImage");
console.log(toURL(test));
You can trick javascript into thinking an image is from your domain with the following code.
image.php
<?php
$image = getAnImagePathAndTypeFromTheDatabaseByID($_GET["id"]);
//returns something like
//array("path" => "http://www.anotherwebsite.com/image.png", "type" => "png")
header("Content-type: image/$image[type]");
echo file_get_contents($image["path"]);
?>
Then just navigate to image.php?id=1 for example.
For it to work in cross-domain client-side you need to call the image with the attribute crossorigin = "true", or, add a line in the Logan Murphy code:
function toURL(image) {
image.setAttribute('crossOrigin', 'anonymous');
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
I use this code:
// image-to-uri.js v1
// converts a URL of an image into a dataURI
function imageToURI(url, callback) {
// Create an empty canvas and image elements
let canvas = document.createElement('canvas');
let img = document.createElement('img');
img.onload = function () {
let ctx = canvas.getContext('2d');
// match size of image
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
// Copy the image contents to the canvas
ctx.drawImage(img, 0, 0);
// Get the data-URI formatted image
callback(null, canvas.toDataURL('image/png'));
};
img.ononerror = function () {
callback(new Error('FailedToLoadImage'));
};
// canvas is not supported
if (!canvas.getContext) {
setTimeout(callback, 0, new Error('CanvasIsNotSupported'));
} else {
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
};
};
which is based on this https://github.com/HenrikJoreteg/image-to-data-uri.js/blob/master/image-to-data-uri.js

Base64 png to Canvas

I'm struggeling with drawing a image on a Canvas.
What I have done so far is that I have inserted imagedata from a Canvas into a database.
The problem is that when I try to create an image of the data and draw it back on the Canvas later it does not draw the same, only some pixels may be drawen while the rest is just blank like nothing should be drawen there.
I'm getting the image data like this:
var CanvasData = document.getElementById('canvas');
CanvasData = CanvasData.toDataURL("image/png");
And drawing the image back on the Canvas like this (the data is stored in a database):
var result = xmlhttp.responseText;
var CanvasDraw = document.getElementById('canvas');
var ctxChange = CanvasDraw.getContext('2d');
imagedata = new Image();
imagedata.src = result;
imagedata.onload = function(){
ctxChange.drawImage(imagedata, 0, 0);
}
Here's a link to pastebin for an example of imagedata: http://pastebin.com/XGmV49k9
Result is the data that is returned from a AJAX call and is the same as what is stored in the database.
Thanks for any help.
Seems that error in this line:
imagedata.src = result;
Should be:
imagedata.src = CanvasData;

Categories

Resources