Solution 1 :

That’s by design. Scaling the canvas will scale everything inside of it by default. Just put the canvas inside a div container with
display: flex;
justify-content: center;
align-items: center;

and scale that.

I’m not 100% clear what you’re hoping to accomplish if that doesn’t work please give a little more detail.

Problem :

I have a canvas that I would like to be able to customize the size of. However, when I set the width and height properties in CSS, the entire canvas is scaled. Additionally, I cannot set it back with ctx.scale(1,1) in JS.

I have already seen this and this question which have no acceptable solution.

Here is my relevant code:

HTML:

<img id="sprites-img" src="roguelikeSheet_transparent.png">
<canvas id="user-map"></canvas>

CSS:

#user-map {
    transform: scale(1,1);
    width: 512px;
    height: 256px;
}

JS:

$( ()=> {
    $('#user-map').click( (evt)=> {
        let clickX = evt.offsetX;
        let clickY = evt.offsetY;

        console.log(clickX, clickY);

        let mapX = Math.floor(clickX/16)*16 ; // not working, scaled incorrectly
        let mapY = Math.floor(clickY/16)*16  ;

        console.log(mapX, mapY);

        placeSprite(mapX, mapY);
    });
});

function placeSprite(mapX, mapY) {
    let startX = selectedSprite[X]*17 - 1;
    let startY = selectedSprite[Y]*17 - 1;

    let ctx = document.getElementById('user-map').getContext('2d');
    ctx.clearRect(mapX, mapY, 16, 16);
    ctx.drawImage(document.getElementById('sprites-img'), startX, startY, 16, 16,
        mapX, mapY, 16, 16);
}

I am aware of the specs of ctx.drawImage(), as described on MDN.

Comments

Comment posted by ChickenSoups

What is

Comment posted by Temani Afif

both question you link have the needed solution which is using attribute instead of CSS. This is how canvas works

Comment posted by Justin

The solution was to do this: canvas.setAttribute(‘width’, window.innerWidth); canvas.setAttribute(‘height’, window.innerHeight);

Comment posted by Justin

Thank you for your answer. I tried adding: #canvas-container { width: 512px; height: 256px; display: flex; justify-content: center; align-items: center; } and

and it still does not work. It just doesn’t scale the canvas at all.

Comment posted by Justin

What I’m trying to do is make the canvas larger (width and height) without it automatically scaling and distorting images drawn on it.

By