Saint Robson
Saint Robson

Reputation: 5525

Put Image Into HTML Canvas (Fit Width and Height)

I have this HTML code :

<div>
    <canvas id="canvas">
    </canvas>
    <img id="canvasimg" src="{{ $photo }}" style="display:none;"/>
</div>

and I have this javascript to draw an image into that HTML Canvas :

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

    var deviceWidth = window.innerWidth;;

    canvasWidth = deviceWidth - 40;
    canvasHeight = deviceWidth - 40;

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

    var img = document.getElementById('canvasimg');

    imgx = 0;
    imgy = 0;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, imgx, imgy); 
</script>

the problem is when I load this page into wide screen, it also produce a wider canvas. while the image has fix width and height.

how to stratch that image so that it will fill the canvas perfectly?

Upvotes: 1

Views: 9729

Answers (1)

Josiah Keller
Josiah Keller

Reputation: 3675

Use the dWidth and dHeight arguments for the drawImage function (MDN).

ctx.drawImage(img, imgx, imgy, canvas.width, canvas.height);

Upvotes: 5

Related Questions