Why is drawing a picture on canvas much larger than the set size?

original image size: 750x1334
canvas size: 750X1334
I"m going to lay a 750x1334 picture as the background on the canvas of 750x1334.

the code is as follows:

 var image = new Image()
  image.src = "/img/background.png"
  image.onload = drawImg // 
  function drawImg () {
context.drawImage(image, 0, 0, 750, 1334)
  }

canvas:

<canvas id="share" canvas-id="share" style="width:750px;height:1334px;">
</canvas>

the result looks like this. The picture on the left is canvas, and the picture on the right is the img of the original image as a comparison, 750x1334, that is, the last effect I want to draw

.

the picture has been stretched a lot. Why?

Jan.18,2022

<canvas id='share' canvas-id='share' width="750" height="1334" style='width:750px;height:1334px;'>
</canvas>
The size of

canvas is not set by style, and the two widths and heights are two different things.


look at you saying that 750x1334 should be for H5 drawing. If you add your dynamic adaptation and open it in the browser to simulate the mobile phone window, it is a drawn picture
but your canvas tag itself is a canvas. I made a Wechat share, front-end drawing, and I posted the code to you. I hope it will be helpful to you

.
var canvas = document.createElement('canvas');
        canvas.width = 750;
        canvas.height = 1206;
        var ctx = canvas.getContext('2d');
        var img = new Image();
        img.onload = function () {
            var img_left = new Image();

            img_left.onload = function () {
                var img_ewm = new Image();
                img_ewm.onload=function(){
                    ctx.font = "24px ";
                ctx.drawImage(img, 0, 0);
                ctx.drawImage(img_left, 310, 160, 115, 115);
                ctx.drawImage(img_ewm, 310, 925, 115, 115);
                ctx.fillStyle = "-sharp773f15";
                ctx.textAlign = 'center';
                ctx.fillText('??', 375, 138);
                //$('body').html(canvas);
                $('.imageShare').attr('src', canvas.toDataURL("image/jpeg"))
                }
                img_ewm.src='./ewm.png';
                img_ewm.crossOrigin = 'anonymous';
                
            }
            img_left.src = "./132.jpeg"
            img_left.crossOrigin = "anonymous";
        }
        img.src = './result2.jpg';
        img.crossOrigin = "anonymous";

pay attention to canvas drawing. Pictures may have cross-domain problems, resulting in unable to generate pictures, so you need to configure the same origin

.
Menu