Maarten Arits
Maarten Arits

Reputation: 180

jquery, resize a canvas without scaling

I was trying to put a canvas in a container. I wanted the canvas to have the same size as the container. To do this I used JQuery, however, this turned out to scale my canvas. This was not my intention, especially because I draw after resizing. Doing seemingly the same thing in good old fashion JavaScript gives me the expected result.

I personally did not expect the JQuery result and it took some time before I figured out the problem. Does anybody know why they opted for this implementation and why it gives a different result? I hope by sharing this I can save some people a lot of time!

Thanks for anybody willing to research this further of fix this!

Here is some example code:

<html>
<head>
    <title>Canvas resizing</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <style type="text/css">
        #container1{
            background-color: green;
            width: 100px;
            height: 100px;
            margin: 50px auto;
        }

        #container2{
            background-color: red;
            width: 100px;
            height: 100px;
            margin: 50px auto;
        }
    </style>
</head>
<body>
    <div id="container1">
        <canvas></canvas>
    </div>
    <div id="container2">
        <canvas></canvas>
    </div>
    <script type="text/javascript">
        function draw (canvas) {
            var context=canvas.getContext("2d");
            context.lineWidth = 5;
            context.rect(25,25,50,50);
            context.stroke();
        }

        $(document).ready(function () {
            //javascript
            var container = document.getElementById('container1');
            var canvas = container.childNodes[1];
            canvas.width = 100;
            canvas.height = 100;
            draw(canvas);

            //jquery
            var container = $('#container2');
            var canvas = container.children()[0];
            $(canvas).width(100);
            $(canvas).height(100);
            draw(canvas);
        });
    </script>
</body>
</html>

Upvotes: 2

Views: 4885

Answers (1)

Brett
Brett

Reputation: 589

The jQuery width and height methods are shorthand aliases for setting the CSS width and height properties. Sizing a canvas using CSS causes the scaled, distorted look you're seeing. Your pure javascript version of the code is setting the width and height attributes of the canvas element. To achieve the same in jQuery you can use:

$(canvas).prop('width', 100)
$(canvas).prop('height', 100)

JSFiddle

Upvotes: 2

Related Questions