35

I have an image which is 1836 x 3264 I want to drawImage() to canvas and resize to 739 x 1162.

After reading the documentation I thought this could be accomplished with the following:

ctx.drawImage(image, 0, 0, 739, 1162);

I have also tried:

ctx.drawImage(image, 0, 0, 1836, 3264, 0, 0, 739, 1162);

Both show only a small part of the full image instead of shrinking it down.

How do I pass through the values to resize from 1836 x 3264 -> 739 x 1162 ?

user229044
  • 232,980
  • 40
  • 330
  • 338
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

1 Answers1

40

What you have looks correct, so you might double-check for a typo somewhere.

[additional thought: Is your image really 1836x3264 and not 3264x1836.]

Here is working code and a Fiddle: http://jsfiddle.net/m1erickson/MLGr4/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    img=new Image();
    img.onload=function(){
        canvas.width=400;
        canvas.height=300;
        ctx.drawImage(img,0,0,img.width,img.height,0,0,400,300);
    }
    img.src="http://www.onestopwebmasters.com/wp-content/uploads/2011/06/eitai-bridge.jpg";

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=100 height=100></canvas>
</body>
</html>
Neuron
  • 5,141
  • 5
  • 38
  • 59
markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    Thanks code was right. It was just a glitch in how the mobile phone system was handling canvas. – Philip Kirkbride Mar 24 '13 at 00:50
  • 1
    @PhilipKirkbride Can you tell us what this mobile phone glitch was and how you fixed it, please? – palsch Aug 24 '16 at 15:13
  • 4
    This answer helped me realize I was setting `canvas.style.width` and `height` rather than `canvas.width`. Changing that helped the `ctx.drawImage` scaling render as expected, rather than the stretching it was doing before the canvas itself had dimension attributes. – crowjonah Nov 10 '17 at 21:21
  • 2
    @crowjonah, Your comment saved a lot of time for me today!. Many thanks. – Nitesh Saxena Aug 20 '18 at 06:03