javascript - Put Image Into HTML Canvas (Fit Width and Height) - Stack Overflow

I have this HTML code :<div><canvas id="canvas"><canvas><img id="c

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?

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?

Share Improve this question asked Aug 14, 2015 at 15:52 Saint RobsonSaint Robson 5,52518 gold badges74 silver badges121 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742418241a4440161.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信