I'm currently trying to add watermark to an image, and I'm using this script:
function mixImages(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imageObj1 = new Image();
var imageObj2 = new Image();
var marginTop = 10;
var marginLeft = 10;
imageObj1.src = "http://localhost:8080/sisop/storage/app/public/files/16522147787.png"
imageObj1.onload = function() {
ctx.drawImage(imageObj1, 0, 0, 328, 526);
imageObj2.src = "http://localhost:8080/sisop/storage/app/public/files/165221397618.png";
imageObj2.onload = function() {
ctx.drawImage(imageObj2, marginLeft, marginTop, 100, 100);
var img = c.toDataURL("image/png");
}
};
}
Which works fine if I'm only doing it with 1 canvas. But I'm trying to do this dynamically to every image that is loaded in my PHP code. so I'm trying to do this:
foreach($collection as $file){
echo "
<div class='posts-cards'>
<canvas id='myCanvas$file->id' width='300' height='300'></canvas>
</div>
<script>
var c=document.getElementById('myCanvas$file->id');
var ctx=c.getContext('2d');
var imageObj1 = new Image();
var imageObj2 = new Image();
var marginTop = 10;
var marginLeft = 10;
imageObj1.src = 'http://localhost:8080/sisop/storage/app/public/files/16522147787.png'
imageObj1.onload = function() {
ctx.drawImage(imageObj1, 0, 0, 328, 526);
imageObj2.src = 'http://localhost:8080/sisop/storage/app/public/files/165221397618.png';
imageObj2.onload = function() {
ctx.drawImage(imageObj2, marginLeft, marginTop, 100, 100);
var img = c.toDataURL('image/png');
}
};
</script>
But for some reason, the result is this:

I have "display: flex; flex-flow: wrap; " in my css (it's supposed to be 2 rows of 4 items in each), so, for some reason, only the 5th and 8th image are being generated.. And as you can see, only the last image has actually "merged" with the other image. I'm pretty stuck in here and don't quite understand what is going on here..