I want draw a line of images with one onload function.
I've tried this code
for(i = 0; i < 8; i++){
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "thumb.png";
imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
context.drawImage(this, this.setAtX, this.setAtY);
};
}
(in java-script)
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("image1.png");
imageURLs.push("image2.png");
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
}
Just reuse the image, and when the image has loaded then draw it in a loop - reorganize like this:
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
for(var i = 0; i < 8; i++) context.drawImage(this, i * 10, i * 10);
// .. call next step from here
};
imageObj.src = "thumb.png";
Try to avoid setting new properties on native objects. In this case you don't need it, just iterate when the image has loaded.
var imageObj = [];
for(var i=0;i<images.length;i++){
iy = parseInt(i/6) * 200;
ix = parseInt(i%6) * 200;
imageObj[i] = new Image();
imageObj[i].src = images[i];
// to set additinal parameter
imageObj[i].ix = JSON.parse(JSON.stringify(ix));
imageObj[i].iy = JSON.parse(JSON.stringify(iy));
// console.log(imageObj);
imageObj[i].onload = function() {
console.log(this.ix);
console.log(this.iy);
ctx.drawImage(this, this.ix, this.iy, 200, 200);
};
}
Related
I am trying to merge multiple images while retrieving the images from desk. It was taken from "How to create an image generator for combining multiple images?". It's working fine if single image is uploaded, but not working in case of multiple images.
This is my HTML code
<input id="file-input" type="file" name="images[]" multiple maxlength="5" ngf-select="UploadFiles($files)" accept=".png,.jpg,.jpeg,.gif" />
<canvas id="canvas"></canvas>
This is javascript code
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var lastImage;
var lastHeight = 0;
var lastWidth = 0;
var imagesLoaded = 0;
function max(a, b) {
if (a > b)
return a;
return b;
}
function addToCanvas(img) {
canvas.height = max(lastHeight, img.width);
canvas.width = lastWidth + img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (lastImage) {
ctx.drawImage(lastImage, 0, canvas.height - lastImage.height);
}
ctx.rotate(270 * Math.PI / 180); // rotate the canvas to the specified degrees
ctx.drawImage(img, -canvas.height, lastWidth);
lastImage = new Image();
lastImage.src = canvas.toDataURL();
lastWidth += img.height;
lastHeight = canvas.height;
imagesLoaded += 1;
}
$scope.UploadFiles = function (files) {
$scope.SelectedFiles = files;
cnt = files.length;
console.log($scope.SelectedFiles);
for (i = 0; i < $scope.SelectedFiles.length; i++) {
console.log(files[i]);
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
addToCanvas(img);
}
img.src = reader.result;
}
reader.readAsDataURL(files[i]);
}
};
When I select images from the folder, the console's debugger stops at img.onload event, where I am trying to do action in loop.
For loop iteration not working for imageload functions..
files.map((file) => {
var reader = new FileReader();
reader.onload = (event) => {
var img = new Image();
img.onload = () =>
{
addToCanvas(img);
}
img.src = reader.result;
}
reader.readAsDataURL(file);
}
)
var canvas = document.getElementById("canvas");
wheel = canvas.getContext("2d");
for (var i = 0; i < 10; i++) {
var img = new Image;
img.src = image;
wheel.drawImage(img, -170, -10, 140, 140);
}
My above code draw only 9(Nine) images but lastOne(10th) image not drawing on canvas. I tried above code but not getting success. Anyone can know solution for this problem.
Can any one help me to find out online JSFiddle Demo which draw image on canvas in loop.
Perhaps your image isn't finished loading before your first draw attempt.
Here is the syntax to make sure your image has finished loading:
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.width = 1100;
canvas.height = 110;
var wheel = canvas.getContext("2d");
var img = document.createElement("img");
img.onload = function() {
for (var i = 0; i < 10; i++) {
wheel.drawImage(img, 5 + 110 * i, 5);
}
};
img.src = "https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100";
EDIT 1 - PROMISES
Working with multiple images:
List sources
map to generates DOM nodes
Setup a Promise per DOM node in a Promise.all
Then draw images
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.width = 1100;
canvas.height = 110;
var wheel = canvas.getContext("2d");
var images = [
"https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=2&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=3&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=4&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=5&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=6&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=7&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=8&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=9&w=100&h=100",
"https://placeholdit.imgix.net/~text?txtsize=60&txt=10&w=100&h=100",
]
.map(function(i) {
var img = document.createElement("img");
img.src = i;
return img;
});
Promise.all(images.map(function(image) {
return new Promise(function(resolve, reject) {
image.onload = resolve;
});
}))
.then(function() {
for (var i = 0; i < images.length; i++) {
var img = images[i];
wheel.drawImage(img, 5 + 110 * i, 5);
}
});
I would do the similar approach to Emil, only difference having a method that loads them individually and once the image is loaded, try to load the next one and so on ...
take a look:
var canvas = document.getElementById("canvas");
// setting canvas size
canvas.height = window.innerHeight - 10;
canvas.width = window.innerWidth - 10;
var image_test = document.querySelector(".hidden");
var count = 0;
var total_images = 10;
var wheel = canvas.getContext("2d");
function loadImage() {
var img = new Image();
img.onload = function() {
wheel.drawImage( this , 105 * count , 0 , 100, 100);
if( count < total_images ) {
count++;
loadImage();
}
}
// img.src = "image-" + count + ".jpg";
img.src = "https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100";
}
loadImage();
https://jsfiddle.net/gugalondon/r5xw6u7L/7
I am using this code to display data of two canvas into third canvas but it is not working.
I am saving the two canvas data using localstorage and passing it to third canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//First canvas data
var img1 = loadImage(localStorage.getItem('cbdata'), main);
//Second canvas data
var img2 = loadImage(localStorage.getItem('cbdata1'), main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if (imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
Your code works. Check that the content of localStorage.getItem is non-empty. And I also slightly modified display of the images by changing ctx.drawImage commands:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//First canvas data
var img1 = loadImage('http://ep01.epimg.net/elpais/imagenes/2015/10/21/ciencia/1445444934_907402_1445781076_portada_normal.jpg', main);
//Second canvas data
var img2 = loadImage('http://ep01.epimg.net/economia/imagenes/2015/10/22/actualidad/1445508003_507635_1445508894_portada_normal.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if (imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0, 100, 100);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 100, 0, 100, 100);
}
}
function loadImage(src, onload) {
console.log('loadImage', src);
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
https://jsfiddle.net/4Le4g8ta/
I have the following code to do so:
img = new Image();
img.src = document.getElementById("input").value;
img.onload = function(){
console.log("loaded");
c.height = img.height;
c.width = img.width;
dimensions =[img.width,img.height];
ctx.drawImage(img,0,0,img.width,img.height);
imageData = ctx.getImageData(0,0,img.width,img.height).data;
ctx.clearRect(0,0,c.width,c.height);
};
However, on google chrome it throws the error Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
Not only that, it's a very complex way of doing a simple action. Any better ways of doing this? If not, help with the error?
What are you trying to do with the data? Depending on that you could possible use the FileReader.readAsDataURL(), especially since you are trying to get the data for the whole image.
Some code:
var input = document.getElementById('file');
var ctx2 = document.getElementById('uploadcanvas').getContext('2d');
var img2 = new Image;
var canvas = document.getElementById('uploadcanvas');
var imgprop = document.createElement("img");
var reader = new FileReader();
ctx2.save();
reader.onloadend = function(e){
imgprop.src = e.target.result
imgprop.onload = function(){
ctx2.restore();
URL.revokeObjectURL(img2.src);
ctx2.clearRect(0, 0, 100,100);
var width = imgprop.width;
var height = imgprop.height;
console.log(width, height);
canvas.width = width;
canvas.height = height;
img2.src = URL.createObjectURL(input.files[0]);
img2.onload = function() {
$('#display-image').css('display', "inline");
ctx2.drawImage(img2, 0, 0);
//URL.revokeObjectURL(img2.src);
};
$("#button").removeAttr("disabled");
$("#button").html("Upload to Facebook");
}
};
reader.readAsDataURL(input.files[0]);
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
function draw()
{
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function()
{
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
}
I have this function in this code two images are placing in canvas but within few sec second img is moving to other place.i want to place both img in canvas how to do?
Try this code, hope this help: DEMO FIDDLE
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);
var img2 = loadImage('http://introcs.cs.princeton.edu/java/31datatype/peppers.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if (imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}