Image resize canvas

后端 未结 2 1372
猫巷女王i
猫巷女王i 2021-01-27 20:30

I\'m trying to upload images and have them fit into different sized boxes....To give you an idea of what the application does: People upload images and have them printed onto po

2条回答
  •  醉梦人生
    2021-01-27 20:57

    Canvas's context.drawImage has a version which allows you to scale an image while you are drawing it to the canvas.

    If you resize disproportionally (like you do in your example) some of your resized image will fall off the canvas. Then your kitty will look distorted (in your example: stretched vertically)

    This sample code resizes proportionally by using only the width. This way your kitty is not stretched.

    // calculate how much to scale the resulting image
    
    var originalWidth=16;
    var originalHeight=20;
    var desiredWidth=20;
    var scalingFactor = desiredWidth/originalWidth;
    
    // scale the original size proportionally
    
    var newWidth=originalWidth*scalingFactor;
    var newHeight=originalHeight*scalingFactor;
    
    // resize the canvas to fit the desired image size
    // Note: canvas is a reference to your html canvas element
    
    canvas.width=newWidth;
    canvas.height=newHeight;
    
    
    // Draw the image to the canvas
    // This version of drawImage allows you to scale the original image
    // while you are drawing it to the canvas.
    
    context.drawImage(
        originalImage,
        0,0,originalWidth,originalHeight,
        0,0,newWidth,newHeight);
    

提交回复
热议问题