简体   繁体   中英

HTML5: canvas and image size

I want to draw an image on canvas using JS. This is my html code:

<canvas style="width:1000px;height:600px;border:1px solid black;" id="canvas"> </canvas>

This is my js code:

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.onload = function(){
      ctx.drawImage(img, 0, 0,1000,600)
    }
    img.src = someUrlToJpgImage;

This is the origin jpg image (1000x600) which is located on server: 在此处输入图片说明

This is the result (1000x600) I see in browser: 在此处输入图片说明

As you see this is scaled the top left corner of the image but not the whole image as expected. I tried to add to js code:

ctx.imageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.mozImageSmoothingEnabled = false;

but it didn't help.

How to solve this problem?

您应该在canvas元素上设置所需的像素数量:

<canvas style="width:1000px;height:600px;border:1px solid black;" height="600" width="1000" id="canvas"> </canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM