0

having problems with javascript image manipulation using html5 canvas objects. What try to do: - i get a base64 encoded image und try to add the filename to the lower left side of the picture the final result

I wrote the following code to solve the problem, but I've got a new problem

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
</head>
<body>
    <textarea style="width: 800px; height: 600px;" id="myTextarea"></textarea>
    <script type="text/javascript">
        var c = document.createElement("CANVAS");
        c.width = 800;
        c.height = 600;
        var ctx = c.getContext("2d");

        var imgData= 'data:image/jpeg;base64,/9j/[abgekürzt]';

        var myImage = new Image();
        myImage.src = imgData;
        ctx.drawImage(myImage, 0, 0);

        // create watermark
        var watermark = "Filename_code_sequentialNumber";
        ctx.font = "20px Courier";
        ctx.textAlign = 'left';
        ctx.fillStyle = 'yellow';
        ctx.fillText(watermark, 20, 580)

        var res = c.toDataURL();

        var c1 = document.createElement("CANVAS");
        c1.width = 800;
        c1.height = 600;
        var ctx1 = c1.getContext("2d");

        var myImage1 = new Image();
        myImage1.src = res;
        ctx.drawImage(myImage1, 0, 0);

        document.body.appendChild(c);
        document.getElementById('myTextarea').value = res;
    </script>
</body>

The current problem is that when i open the site in my Browser i only see the watermark on a blank white image. After a reload of the site i get the desired result ob the image with the watermark on it.

Has anyone any idea how to solve the reload problem ?

Tomben
  • 73
  • 7
  • You may need to wait for the image to load before rendering it. `myImage.src = imgData; myImage.onload = function() { doStuff(); }` – Mike Cluck Feb 18 '16 at 22:48
  • Hi Mike C when i add the following code myImage.onload = function(){ // create watermark ctx.fillText(watermark, 20, 20); }` i get only the picture without the watermark :( – Tomben Feb 19 '16 at 20:02
  • Did you try drawing the image inside of the `onload` handler? I haven't worked much with data URI's so I don't know if that's the problem or not. – Mike Cluck Feb 19 '16 at 20:04
  • Hi Mike, i tried the following code `var myImage1 = new Image(); myImage1.src = res; ctx.drawImage(myImage1, 0, 0); myImage1.onload = function(){ ctx.font = "20px Courier"; ctx.textAlign = 'left'; ctx.fillStyle = 'yellow'; // create watermark ctx.fillText(watermark, 20, 20); }` but nothing happens, it seems that the inner circle commands never called :( ! Any ideas ? – Tomben Feb 22 '16 at 10:46
  • 1
    Look at [this question](http://stackoverflow.com/questions/4776670/should-setting-an-image-src-to-data-url-be-available-immediately) for tips on how to fix it. – Mike Cluck Feb 22 '16 at 16:15

0 Answers0