I have the following code:
var imageLoader = document.getElementById('imageLoader');
var patternLoader = document.getElementById("patternLoader");
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]);
};
imageLoader.addEventListener("change", handleImage, false);
patternLoader.addEventListener("change", handleImage, false);
How can I load one image over another from inputs and not replace them?
I want it to be like that http://i.gyazo.com/85c8c6bdcd2efcdd6a1c1b156000f204.png
Here's a crude way to add images dynamically. Declare an array to keep track on all your images and scale the canvas based on the largest image.
Since I didn't konw what kind of DOM elements the OP used for "imageLoader" and "patternLoader", I simply used an <input>-tag.
Just keep pasting URLs for images to add images to your canvas. The images will be drawn in the order as you add them.
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var maxWidth = 0;
var maxHeight = 0;
var images = [];
var myInput = document.getElementById("myInput");
myInput.addEventListener('change',handleImage,false);
function handleImage(e) {
var myImage = new Image();
myImage.onload = function () {
if (myImage.width > maxWidth) {
maxWidth = myImage.width;
}
if (myImage.height > maxHeight) {
maxHeight = myImage.height;
}
canvas.width = maxWidth;
canvas.height = maxHeight;
images.push(myImage);
drawImages();
}
myImage.src = e.target.value;
}
function drawImages() {
for (var i = 0; i<images.length; i++) {
ctx.drawImage(images[i],canvas.width/2-images[i].width/2,canvas.height/2-images[i].height/2);
}
}
<input type="text" id="myInput"><br />
<canvas id="canvas"></canvas>
Related
How do I only accept photos (from the file explorer) smaller that 1920x1080. Otherwise, my entire webpage get flooded with one image. Here is my code for importing the photos:
Html:
<input type="file" id="file" accept="image/png, img/jpeg">
Javascript:
function Read(){
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e) {
var image = document.createElement("img");
// the result image data
image.src = e.target.result;
document.body.appendChild(image);
}
reader.readAsDataURL(file);
}
You can use Canvas to resize bigger images.
<input type="file" id="file" accept="image/png, img/jpeg" #change="selectFile">
selectFile: function (list)
{
const self = this, limitWidth = 1920, limitHeight = 1080, len = list.length;
let i, item, cnt = len;
events.$emit('show_spinner');
for(i=0;i<len;i++)
if(list[i].size)
{
item = list[i];
const reader = new FileReader(), img = new Image(), canvas = document.createElement('canvas');
reader.onload = function (e)
{
img.v_name = this.v_name;
img.v_size = this.v_size;
img.src = e.target.result;
};
reader.onerror = function ()
{
events.$emit('hide_spinner');
};
img.onerror = function ()
{
events.$emit('hide_spinner');
};
img.onload = function ()
{
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
// preserve aspect ratio
if(canvas.width > limitWidth)
{
canvas.width = limitWidth;
canvas.height = limitWidth * img.naturalHeight / img.naturalWidth;
}
if(canvas.height > limitHeight)
{
canvas.height = limitHeight;
canvas.width = limitHeight * img.naturalWidth / img.naturalHeight;
}
// implicit width and height in order to stretch the image to canvas
canvas.getContext("2d").drawImage(img, 0, 0, canvas.width, canvas.height);
self.fileArray.push(
{
name: this.v_name,
size: this.v_size,
src: canvas.toDataURL('image/jpeg', 0.8),
id: Date.now()
}
);
cnt--;
if(cnt==0) events.$emit('hide_spinner');
};
reader.v_name = item.name;
reader.v_size = item.size;
reader.readAsDataURL(item);
}
},
You don't need to check the image size. you can just use css for resizing the image so it doesn't fill up the page.
img {
width: 100%;
max-width: 300px;
/** height will be automatically calculated */
}
this way images won't be wider than 300 pixels and they won't fill up your entire page.
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 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);
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
I need help with the following resource http://www.filmfans.cz/test/index2.html
I don't know how to change the colours of the pinquen after the click on the sample.
I would like to do something similar as in the following link http://www.pixelbox.sk/fileadmin/Flash/cosmo_2.swf
Here is my code
$(window).load(function(){
var width = $(window).width();
var height = $(window).height();
var c = document.getElementById("a");
var ctx = c.getContext("2d");
var can2 = document.createElement('canvas');
document.body.appendChild(can2)
can2.width = c.width;
can2.height= c.height;
var ctx2 = can2.getContext("2d");
var test= new Image();
test.src = "tux.png";
test.onload = function() {
ctx2.drawImage(test, 0, 0);
}
var img = new Image();
img.src = "2.png";
img.onload = function(){
ctx2.globalCompositeOperation = "source-in";
var pattern = ctx2.createPattern(img, "repeat");
ctx2.fillStyle=pattern;
ctx2.fillRect(0,0,300,300);
}
});
$(document).ready(function () {
$('.klik').click(function() {
var adresa = $(this).children('img').attr('src');
var canvas = document.getElementById("a");
canvas.width = canvas.width;//blanks the canvas
var c = canvas.getContext("2d");
var img = new Image();
img.src = adresa;
img.onload = function(){
var pattern = c.createPattern(img, "repeat");
//c.globalCompositeOperation = "source-in";
c.fillStyle=pattern;
c.fillRect(0,0,300,300);
}
// c.drawImage(img, 0, 0);
//}
//return false;
});
});
</code>
</pre>
Problem solved !
Using a second, temporary canvas with source-in is the right idea:
ctx2.drawImage(test, 0, 0);
ctx2.globalCompositeOperation = 'source-in';
var ptrn = ctx2.createPattern(pattern,'repeat');
ctx2.fillStyle = ptrn;
ctx2.fillRect(0,0,300,300);
ctx.drawImage(can2,0,0)
live example:
http://jsfiddle.net/UcGrC/