Saint Robson
Saint Robson

Reputation: 5525

Perfectly Load Image Into HTML Canvas

I have this code to load image into HTML canvas :

<div class="col-md-6 col-md-offset-3 text-center" style="padding: 20px;">
    <canvas id="canvas">
        bad browser. canvas is not supported.
    </canvas>
    <img id="canvasimg" src="kindle.jpg" style="display:none;"/>
</div>

<script>
    var canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');

    var deviceWidth = window.innerWidth;;

    canvasWidth = 300;
    canvasHeight = 300;

    canvas.width = canvasWidth;
    canvas.height = canvasHeight;

    var img = document.getElementById('canvasimg');
    imgx = canvas.width/2 - img.width/2;
    imgy = canvas.height/2 - img.height/2;

    function runLoop(){             
        ctx.lineWidth  = 8;
        ctx.font = '20pt Lato';
        ctx.strokeStyle = 'black';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        ctx.lineJoin = 'round';

        var text1 = document.getElementById('canvastext-top').value;
        //text1 = text1.toUpperCase();

        var text2 = document.getElementById('canvastext-bottom').value;
        //text2 = text2.toUpperCase();

        x = canvas.width/2;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, imgx, imgy);

        ctx.strokeText(text1, x, 60);
        ctx.fillText(text1, x, 60);

        ctx.strokeText(text2, x, 270);
        ctx.fillText(text2, x, 270);

        window.setTimeout(runLoop, 14);
    };
    runLoop();


    var download = document.getElementById('img-download');
    download.addEventListener('click', prepareDownload, false);

    function prepareDownload() {
        var data = canvas.toDataURL();
        download.href = data;
    }

</script>

now, here's the case... when I open that page for the first time, the image isn't properly loaded. It look like this :

enter image description here

but when I tried to refresh or open that same page for second time, it perfectly loaded :

enter image description here

Upvotes: 0

Views: 113

Answers (1)

wilovent
wilovent

Reputation: 1364

replace ctx.drawImage(img, imgx, imgy) by ctx.drawImage(img, 0, 0)

x and y don't refer to the center of the picture, but the top left corner.

Upvotes: 1

Related Questions