Answer the question
In order to leave comments, you need to log in
Why is the picture not applied to the canvas?
There is a script that sculpts watermarks on all images found on the page. Of course, it does not work for modal windows in which images are loaded via Ajax. I added a script to the end of the php file loaded by Ajax, which should make watermarks for those images that are loaded, but the script behaves crookedly in 80% of cases: it does not apply the main image to the canvas. Just hangs a watermark on an empty canvas. How to be?
The code of the file that is loaded by Ajax.
<div class="img_modal" data-id="<?= $img_id ?>" id="img_<?= $img_id ?>">
<span class="img_alt" id="alt_img_<?=$img_id?>" data-id="<?=$img_id?>"></span>
<?= $image ?>
<script>
$('#img_'+<?=$img_id?>).children('img').attr('id', 'watermark_modalsource' + <?=$img_id?>);
var imgWidth = $('#watermark_modalsource'+<?=$img_id?>).width();
var imgHeight = $('#watermark_modalsource'+<?=$img_id?>).height();
$('#watermark_modalsource'+<?=$img_id?>).parent().append("<canvas class='watermarked_canvas'>");
$('#watermark_modalsource'+<?=$img_id?>).next().next('canvas').attr('width', imgWidth);
$('#watermark_modalsource'+<?=$img_id?>).next().next('canvas').attr('height', imgHeight);
$('#watermark_modalsource'+<?=$img_id?>).next().next('canvas').attr('id', 'watermarkcanvas');
var c = document.getElementById('watermarkcanvas');
var ctx = c.getContext("2d");
var img = document.getElementById('watermark_modalsource' + <?=$img_id?>);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
var img2 = document.getElementById("watermark");
ctx.drawImage(img2, 0, 0, imgWidth, imgHeight);
var canvas = document.getElementById('watermarkcanvas');
var dataURL = canvas.toDataURL();
$('#watermark_modalsource'+<?=$img_id?>).attr('src', dataURL);
$('#watermarkcanvas').remove();
$('.watermarked_canvas').remove();
</script>
</div>
Answer the question
In order to leave comments, you need to log in
I suspect that at the moment the script is executed, the image has not yet been loaded.
Try to hang the code on the load event of the picture:
a). or by pointing directly at the element onload="makeWatermark()"
,
b). or with $('img').on('load', makeWatermark)
, but in this case SRC should be specified only after hanging the event handler.
in). (IMHO - the best option) Do not load images into the DOM at all, load only a link to the image, and on the JS side, already create an image and work with it:
var img = document.createElement('img');
img.onload = makeWatermark;
img.src = "<?=$img_url;?>";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question