0

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Justin
  • 945
  • 12
  • 26

1 Answers1

0

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.

  • 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.
    – Justin Feb 13 '20 at 07:27
  • What I'm trying to do is make the canvas larger (width and height) without it automatically scaling and distorting images drawn on it. – Justin Feb 13 '20 at 07:29