I have two html img objects with different src urls. I’d like to combine these two images (using canvas), and create one merged img object. I want to give user to select a image from his location and second image will be logo and user can change the location of logo and when click on post button one image object is generated and able to save in database. I am getting one error while writting this javascript object type mismatch I do not under where is the issue…
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
<form name="drawImage" id="drawImage">
<input type="file" id="filename" name="filename" value="hello" />
<canvas id="mycanvas" width="400" height="400"></canvas>
<input type="button" id="mybtn" name="mybtn" value="hello" />
</form>
<script>
$(function(){
var canvas,ctx,img1,img2;
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
if(imagesLoaded == 2) {
// composite now
console.log(img1);
ctx.drawImage(img1, 0, 0);
//ctx.globalAlpha = 1;
ctx.drawImage(img2, 0,100);
}
}
function loadImage(src, onload) {
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
function drawImages(){
var img1 = loadImage('http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);
var img2 = loadImage('http://blog.carazoo.com/wp-content/uploads/2010/11/skoda_logo-300x300.jpg', main);
}
$("#mybtn").click(function(){
//var getImageInput=$("#filename").val();
//var img1 = loadImage(getImageInput, main);
//var img2 = loadImage('play-button.png', main);
drawImages();
});
});
</script>
</body>
</html>
The problem is that
img1andimg2are locally redeclared insidedrawImages()and thus theimg1andimg2variables inside themain()scope point to the undefinedimg1andimg2in your global scope. The same goes forcanvasandctx, although this doesn’t cause any issues since they’re only used insidemain().In short, you can “fix” this by removing the
varinsidedrawImages():Additionally, you could remove the
canvasandctxfrom the global scope, since they’re only used insidemain().However, you might want to do a more thorough rewrite of your code and properly scope your variables. You want to load the two images first and then render them on the canvas. Those are two distinct problems and it’s better to separate the code dealing with them.