Home > Software engineering >  Why is image stretched on canvas?
Why is image stretched on canvas?

Time:08-29

I specified the image dimensions to be 50px by 50px but it is stretched on the y axis like this. Stretched Image

I think it may have something to do with the css styling so here is my css code.

canvas {
    background-color: green;
    padding: 0;
    margin: auto;
    display: block;
    height: 700px;
    width: 700px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

Please tell me why the image is stretched.

CodePudding user response:

css width and height doesn't update the initial aspect ratio of canvas, which is introduced to the element by the attributes like this: <canvas width="X" height="Y">

If the size of your canvas is fixed, you should change the width and height of the canvas tag attributes.

If it's not constant, you may need to use Javascript to update it, like this:

const canvasDom = document.getElementById('mycanvas');
canvasDom.setAttribute('width', '700');
canvasDom.setAttribute('height', '700');
  • Related