Combining 2 images in javascript - javascript

So I know this question has been asked before; however, for some reason I cannot get the height and width of my canvas to display correctly.
Here is what I currently have, but for some reason the image gets cut off and does not display the entire image. Any thoughts? Thanks!
function mergeImages(source1, source2){
let image1 = new Image();
image1.src = source1;
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
image1.onload = function (){
c.width = image1.width;
ctx.drawImage(image1, 0, 0, image1.width, image1.height);
let image2 = new Image();
image2.src = source2;
image2.onload = function (){
ctx.drawImage(image2, 0, image1.height, image2.width, image2.height);
console.log(c.toDataURL("image/png"));
};
};
}

You are making the assumption that image1 is loaded before image2, this might be 99% true.
I suggest you get the images first and then write it to the canvas. In your current code you are setting the width and not the height
Attaching two solutions
This is based on what you have, with just some changes around canvas width and height
function mergeImages(source1, source2){
let image1 = new Image();
image1.src = source1;
var c = document.getElementById('canvas');
var ctx = c.getContext("2d");
image1.onload = function (){
let image2 = new Image();
image2.src = source2;
image2.onload = function (){
c.width = Math.max(image1.width, image2.width)
c.height = image1.height + image2.height
ctx.drawImage(image1, 0, 0, image1.width, image1.height);
ctx.drawImage(image2, 0, image1.height, image2.width, image2.height);
console.log(c.toDataURL("image/png"));
};
};
}
mergeImages('https://i.imgur.com/5HtV0Nv.jpg', 'https://i.imgur.com/5HtV0Nv.jpg')
This is based on promises
function loadImage(url) {
return new Promise(resolve => {
const img = new Image();
img.addEventListener('load', () => {
resolve(image);
});
img.src = url;
});
}
async function asyncMergeImages(source1, source2){
let c = document.getElementById('canvas');
let ctx = c.getContext("2d");
let image1 = await loadImage(source1)
let image2 = await loadImage(source2)
c.width = Math.max(image1.width, image2.width)
c.height = image1.height + image2.height
ctx.drawImage(image1, 0, 0, image1.width, image1.height);
ctx.drawImage(image2, 0, image1.height, image2.width, image2.height);
console.log("async",c.toDataURL("image/png"));
}
asyncMergeImages('https://i.imgur.com/csFntM8.jpg', 'https://i.imgur.com/5HtV0Nv.jpg')

Related

getImageData returns white image

I need to read the image data from an image object in javascript.
But my code returns always a blank array (set to 255)
<html>
<header>
</header>
<body>
<input type="file" id="imgfile" onchange="testImageData(event);" />
<canvas id="canvas1" width="640" height="480"></canvas>
<script src="./../scripts/cam.js" ></script>
</body>
</html>
Here is the script
var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d');
function getImageData(image){
/*
returns Uint8ClampedArray object
takes an image obj
*/
var canvas = document.createElement("canvas");
canvas.height = image.height;
canvas.width = image.width;
var ctx = canvas.getContext("2d");
ctx.width = image.width;
ctx.height = image.height;
ctx.drawImage(image,0,0);
return ctx.getImageData(0, 0, ctx.width, ctx.height);
}
function testImageData(event){
var selectedFile = event.target.files[0];
var reader = new FileReader();
var img = new Image();
reader.onload = function(event) {
console.log('onload');
img.src = event.target.result;
img.onload = function(){
context1.drawImage(img, 0,0, img.width, img.height);
var imgData = getImageData(img);
// console.log(imgData);
var data = imgData.data;
for(var i = 0; i<data.length;i+=4){
console.log(data[i],data[i+1],data[i+2],data[i+3]);
}
}
};
In my understanding, the console.log should return me the data in RGBA.
But I'm just getting 255.
console.log output
EDIT:
Okay I found a work around but I don't understand why this is working.
Instead using getImageData, I get the data directly from the drawn context1.
function testImageData(event){
var selectedFile = event.target.files[0];
var reader = new FileReader();
var img = new Image();
reader.onload = function(event) {
console.log('onload');
img.src = event.target.result;
img.onload = function(){
context1.drawImage(img, 0,0, img.width, img.height);
var imgData = context1.getImageData(0,0,img.width,img.height);
var data = imgData.data;
for(var i = 0; i<data.length;i+=4){
console.log(data[i],data[i+1],data[i+2],data[i+3]);
}
}
};
So the problem must lie in creating a new canvas.
You should wait for the image to load img.onload you are waiting for the readers onload event...
you also forget to read the file... missed reader.readAsDataURL
but you don't need the filereader.
window.URL = window.URL || webkitURL
var img = new Image();
img.src = URL.createObjectURL(file)
img.onload = function(){
// put your image on the canvas
}

HTML 5 Canvas image overlay repeatable

I am trying to take a pattern and apply it over a png image but only cover the non-transparent part of the image similar to this one.
http://jsfiddle.net/eLmmA/1/
$(function() {
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var canvas_context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
var msk = new Image();
msk.onload = function(){
canvas_context.drawImage(img, 0, 0);
canvas_context.globalCompositeOperation = "destination-in";
canvas_context.drawImage(msk, 0, 0);
canvas_context.globalCompositeOperation = "source-over";
};
msk.src = 'http://i.stack.imgur.com/QtQrZ.png';
}
img.src = 'http://i.stack.imgur.com/MDGFY.jpg';
document.body.appendChild(canvas);
});
The example above is really close to what I want but I need to be able to use a smaller texture image and repeat it over the none pattern image. I am not familiar with how to use canvas properly but trying to learn more about it.
Thanks in advance!
Never mind I figured it out.
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var canvas_context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
var msk = new Image();
msk.onload = function(){
var ptrn = canvas_context.createPattern(img, 'repeat');
canvas_context.fillStyle = ptrn;
canvas_context.fillRect(0, 0, canvas.width, canvas.height);
canvas_context.drawImage(img, 0, 0);
canvas_context.globalCompositeOperation = "destination-in";
canvas_context.drawImage(msk, 0, 0);
canvas_context.globalCompositeOperation = "source-over";
};
msk.src = $('#base_url').data('base')+'assets/themes/img/download.png';
}
img.src = $('#base_url').data('base')+'assets/uploads/thumbs/1381413411Purple-Night-Owls-thumb.jpg';
$('#itemPreview').html(canvas);

Combine two images in one canvas

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/

Javascript combine Images

I tried everything to get this work but didn't happen.
Want a method to combine two images (that they are overlayed somehow).
I tried it like described here: Merge Image using Javascript
With this Code:
var c=document.createElement("canvas");
c.width = 100;
c.height = 100;
var ctx=c.getContext("2d");
var imageObj1 = new Image();
imageObj1.src = base64String;
var imageObj2 = new Image();
imageObj1.onload = function() {
ctx.drawImage(imageObj1, 0, 0, 328, 526);
imageObj2.src = "2.png";
imageObj2.onload = function() {
ctx.drawImage(imageObj2, 15, 85, 300, 300);
var img = c.toDataURL("image/png");
}
};
But it doesn't work.
I get the first image by Base64 from Local Storage (as described here) like this:
var img = new Image();
img.src = base64String;
And the base64 String looks like this: data:image/png;base64,iVBORw0KGgoAAAANS....
Does this somehow break this approach with canvas?
Any help is appreciated :) took me already hours and can't figure it out....
Fixed it like this:
var c = document.createElement('canvas');
c.width = 82;
c.height = 75;
var ctx = c.getContext("2d");
var imageObj2 = new Image();
imageObj2.onload = function (){
ctx.drawImage(imageObj2, 0, 0, 82, 75);
var imageObj1 = new Image();
imageObj1.onload = function (){
imageObj1.style.objectFit = "cover";
ctx.drawImage(imageObj1, 14, 4, 53, 53);
};
imageObj1.src = data.elephant;
};
imageObj2.src = "2.png";

How to place the two images in single canvas using asp.net?

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;
}

Categories

Resources