完美地将图像加载到HTML画布中

时间:2015-07-27 07:50:07

标签: jquery html canvas

我有这段代码将图片加载到HTML画布中:

<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>

现在,就是这样......当我第一次打开该页面时,图像没有正确加载。它看起来像这样:

enter image description here

但是当我第二次尝试刷新或打开同一页时,它完全加载了:

enter image description here

1 个答案:

答案 0 :(得分:1)

ctx.drawImage(img, imgx, imgy)替换为ctx.drawImage(img, 0, 0)

x和y不是指图片的中心,而是左上角。