I'm working with canvas and I have a script that uploads an image from user desktop and I need to change it to load images from the same page and put them on canvas (uploaded files from desktop go directly to canvas already).
the functions:
window.onload=function(){
var s = document.getElementById("fontsize");
s.value="48";
document.getElementById('loadpicture').addEventListener('change', aFileIsLoaded, false);
backgroundimagemode=NONE;
carpeInit();
update();
}
and:
function aFileIsLoaded(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = function(e2)
{
backgroundimage = new Image();
backgroundimage.src=e2.target.result;
};
fr.readAsDataURL(filename);
}
Thank you
It's my first question here, I think I wrote before in the wrong box, sorry
I have now this code as you suggested
function aFileIsLoaded(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = function(e2)
{
backgroundimage = new Image();
backgroundimage.src=e2.target.result;
var context = document.getElementById('myCanvas').getContext('2d');
context.canvas.width = backgroundimage.width;
context.canvas.height = backgroundimage.height;
context.drawImage(backgroundimage, 0, 0, backgroundimage.width, backgroundimage.height);
};
fr.readAsDataURL(filename);
}
before, the image was loaded from desktop with
<input type="file" name="backpicture" id="loadpicture">
How can I call now from a list of images?
thank you
Assuming you have a canvas in the document with the id myCanvas you can add this to the fr.onload function you have now.
var context = document.getElementById('myCanvas').getContext('2d');
context.canvas.width = backgroundimage.width;
context.canvas.height = backgroundimage.height;
context.drawImage(backgroundimage, 0, 0, backgroundimage.width, backgroundimage.height);
wow, very fast, thank you
in this way without deleting anythin?
function aFileIsLoaded(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = function(e2)
{
var context = document.getElementById('myCanvas').getContext('2d');
context.canvas.width = backgroundimage.width;
context.canvas.height = backgroundimage.height;
context.drawImage(backgroundimage, 0, 0, backgroundimage.width, backgroundimage.height);
backgroundimage = new Image();
backgroundimage.src=e2.target.result;
};
fr.readAsDataURL(filename);
}
Related
I need some help with code review and re-translate it out of jQuery to plain JS.
I've tried to translate this into pure JS, but I don't get clearly why it doesn't work. If needed, I can show what I've made.
After the user selects an image from the first input, it should be rendered on canvas.
After the user selects an image from the second input, it should be rendered on the same canvas to the right of the first image.
Images should be rendered in scale, so two pictures will have the same height on canvas, but with the original aspect ratio.
User can select images in any order, but rendering order should stay the same: image from first input appears on canvas before image from the second input.
Inputs should accept only images.
$('.file1, .file2').on('change', function() {
var reader = new FileReader(),
imageSelector = $(this).data('image-selector');
if (this.files && this.files[0]) {
reader.onload = function(e) {
imageIsLoaded(e, imageSelector)
};
reader.readAsDataURL(this.files[0]);
}
});
$('.btn-merge').on('click', merge);
function imageIsLoaded(e, imageSelector) {
$(imageSelector).attr('src', e.target.result);
$(imageSelector).removeClass('hidden');
};
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
imageObj1.src = $('.image1').attr('src');
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 328, 526);
imageObj2.src = $('.image2').attr('src');;
imageObj2.onload = function() {
ctx.globalAlpha = 0.5;
ctx.drawImage(imageObj2, 15, 85, 300, 300);
var img = canvas.toDataURL('image/jpeg');
$('.merged-image').attr('src', img);
$('.merged-image').removeClass('hidden');
}
};
}
You should define the onload before changing source and not inside another onload
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 328, 526);
}
imageObj2.onload = function() {
ctx.globalAlpha = 0.5;
ctx.drawImage(imageObj2, 15, 85, 300, 300);
var img = canvas.toDataURL('image/jpeg');
$('.merged-image').attr('src', img);
$('.merged-image').removeClass('hidden');
}
imageObj1.src = $('.image1').attr('src');
imageObj2.src = $('.image2').attr('src');
}
I want to check for the size of image, and then display the image as a cropped version by defining the set size(w*h).
How can i do this?
This is the code I have tried:
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
<input type="file" onchange="handleFiles(this.files[0])" id="inputFileToLoad">
<canvas id="canvas"></canvas>
function handleFiles(fileToLoad) {
if (fileToLoad.type.match("image.*")) {
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var img = new Image();
img.onload = function () {
var canvas = document.getElementById("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// cropped = ctx.getImageData(x, y, crop_width, crop_height);
cropped = ctx.getImageData(500, 500, 200, 200);
// clearing is optional ... new img is over the old one
ctx.clearRect(0, 0, canvas.width, canvas.height);
// re-size canvas to croped img size
canvas.width = 200;
canvas.height = 200;
ctx.putImageData(cropped, 0, 0)
};
img.src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
draw the imageLoaded into canvas of the size w*h shifted by some position
get the image data by yourcanvas.toDataUrl()
place the image data into image element
The function that does this
function getImagePortion(imgObj, newWidth, newHeight, startX, startY, ratio){
/* the parameters: - the image element - the new width - the new height - the x point we start taking pixels - the y point we start taking pixels - the ratio */
//set up canvas for thumbnail
var tnCanvas = document.createElement('canvas');
var tnCanvasContext = canvas.getContext('2d');
tnCanvas.width = newWidth; tnCanvas.height = newHeight;
/* use the sourceCanvas to duplicate the entire image. This step was crucial for iOS4 and under devices. Follow the link at the end of this post to see what happens when you don’t do this */
var bufferCanvas = document.createElement('canvas');
var bufferContext = bufferCanvas.getContext('2d');
bufferCanvas.width = imgObj.width;
bufferCanvas.height = imgObj.height;
bufferContext.drawImage(imgObj, 0, 0);
/* now we use the drawImage method to take the pixels from our bufferCanvas and draw them into our thumbnail canvas */
tnCanvasContext.drawImage(bufferCanvas, startX,startY,newWidth * ratio, newHeight * ratio,0,0,newWidth,newHeight);
return tnCanvas.toDataURL();
}
is step by step described here
Thank you guys,
Using Canvas is the right approach here. This is my final piece of code
Here is the final Code:
Ref Link
<html>
<title>
Upload Image
</title>
<div style="text-align: center">
<h1>: UPLOAD IMAGE : </h1>
</div>
<div>
<input type="file" id="imageLoader" name="imageLoader" onchange="checkFileDetails()"/>
<br/>
<h3>Horizontal<h3>
<canvas id="imageCanvas1"></canvas>
<br/>
<h3>Vertical<h3>
<canvas id="imageCanvas2"></canvas>
<br/>
<h3>Horizontal Small<h3>
<canvas id="imageCanvas3"></canvas>
<br/>
<h3>Gallery<h3>
<canvas id="imageCanvas4"></canvas>
</div>
<script>
//Check for the image Size and type
// Display Image in the required format
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage1, false);
var canvas1 = document.getElementById('imageCanvas1');
var ctx1 = canvas1.getContext('2d');
function handleImage1(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas1.width = 755;
canvas1.height = 450;
ctx1.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader1 = document.getElementById('imageLoader');
imageLoader1.addEventListener('change', handleImage2, false);
var canvas2 = document.getElementById('imageCanvas2');
var ctx2 = canvas2.getContext('2d');
function handleImage2(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas2.width = 365;
canvas2.height = 450;
ctx2.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader2 = document.getElementById('imageLoader');
imageLoader2.addEventListener('change', handleImage3, false);
var canvas3 = document.getElementById('imageCanvas3');
var ctx3 = canvas3.getContext('2d');
function handleImage3(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas3.width = 365;
canvas3.height = 212;
ctx3.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader3 = document.getElementById('imageLoader');
imageLoader3.addEventListener('change', handleImage4, false);
var canvas4 = document.getElementById('imageCanvas4');
var ctx4 = canvas4.getContext('2d');
function handleImage4(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas4.width = 380;
canvas4.height = 380;
ctx4.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
</script>
i'm currently trying to load a base64 img into my canvas
console.log('Change');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = stack[1].save;
stack[1].save contains a valid base64 png img URL('data:image/png;base64,xxxxxx'), when i paste this URL into my browser i can see a valid img
The fact is that nothing changes and i dont have any error
If you could help me this will be awesome, thank's
Yes the code you have shared should work OK.
Here is an example
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
var image = new Image();
image.onload = () => { ctx.drawImage(image, 0, 0) }
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAQAAAAngNWGAAAAF0lEQVR42mNk+M9AFGAcVTiqcFQhCAAAf0sUAaSRMCEAAAAASUVORK5CYII="
var image2 = new Image()
image2.onload = () => { for(i=1; i<9; i++) ctx.drawImage(image2, 30*i, 5+4*i) }
image2.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg=="
<canvas id="canvas"></canvas>
The only thing that could be wrong is that stack[1].save that you are using...
Trying to separate image loading on canvas functionality.
It works perfect like that
html
<label>Image File:</label>
<br/>
<input type="file" id="imageLoader" name="imageLoader" />
<canvas id="imageCanvas"></canvas>
javascript
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
http://jsfiddle.net/influenztial/qy7h5/
But when I trying to separate it, it stucks because of event.target.result is becaming undefind for some reason.
Code is here
http://jsfiddle.net/qy7h5/1840/
Whats wrong? is there some best practice about that?
You need to understand the code first right. Try my code which works fine.
Where I remove event cast and Image onload cast , also remove Image as argument which had been worked as event not image object.
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
onReaderLoad(event);
}
reader.readAsDataURL(e.target.files[0]);
}
var onReaderLoad = function(event) {
var image = new Image();
image.onload = function() {
onImageLoad(image);
}
image.src = event.target.result;
}
var onImageLoad = function(img) {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
I update fiddle here
Like the title says, I have a byte array representing the contents of an image (can be jpeg or png).
I want to draw that on a regular canvas object
<canvas id='thecanvas'></canvas>
How can I do that?
UPDATE I tried this (unsuccesfully):
(imgData is a png sent as a byte array "as is" through WebSockify to the client)
function draw(imgData) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rdr = new FileReader();
var imgBlob = new Blob([imgData], {type: "image/png"});
rdr.readAsBinaryString(imgBlob);
rdr.onload = function (data) {
console.log("Filereader success");
var img = new Image();
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
img.src = "data:image/png;base64," + window.btoa(rdr.result);
};
}
I always reach img.onerror()
Also After reading the file with a HEX editor on my file system, I can see that the byte array is identical to the original file.
This Works:
function draw2(imgData, coords) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//var uInt8Array = new Uint8Array(imgData);
var uInt8Array = imgData;
var i = uInt8Array.length;
var binaryString = [i];
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var img = new Image();
img.src = "data:image/png;base64," + base64;
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, coords[0], coords[1], canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
}