Vinay
Vinay

Reputation: 743

HTML5 Canvas drawImage issue

I am using a cropper.js library to get the cropping coordinates from the image and then i am creating a canvas to download the cropped image.

i have fixed cropping dimensions max at 200x200 pixels

The issue is that the cropped image does not stretch fully to 200 px width of the canvas that it should. See the image below

enter image description here

Check this fiddle (thanks @entio for the fiddle)

Below is the code

<body>
        <img src="Desert.jpg" id="image" style="float:left;"/>
        <canvas id="myCanvas" style="height:200px; width:200px; position:absolute; right:50px; top:20px; border:1px dotted black;"></canvas>
        <div>
        <label><em>y</em>coordinate</label>                                
        <input type="text" name="y" id="y-1" class="form-control" value="0" />

        <label><em>x</em> coordinate</label>                                
        <input type="text" name="x" id="x-1" class="form-control" value="0" />

        <label>Selected <em>width</em></label>                                
        <input type="text" name="width" id="width-1" class="form-control" value="0" />

        <label>Selected <em>height</em></label>                                
        <input type="text" name="width" id="height-1" class="form-control" value="0" />                                
     </div>                   

    </body>
    <script type="text/javascript">
        document.getElementById('image').onload = function() {
            new Cropper(image, {
                // options              
                max_width: 200,
                max_height: 200,                    
                update: function(coordinates) {
                    console.log(coordinates);
                    console.log(image);                     
                    for (var i in coordinates) {
                        document.getElementById(i + '-1').value = coordinates[i];
                    }
                    var canvas = document.getElementById('myCanvas');
                    var context = canvas.getContext('2d');                  
                    context.drawImage(image, coordinates['x'],coordinates['y'], coordinates['width'],coordinates['height'], 0, 0, 200, 200);
                }
            });
        }
    </script>

Any help ?

Upvotes: 2

Views: 820

Answers (1)

miguel-svq
miguel-svq

Reputation: 2176

Canvas use width and height attributes.

<canvas id="myCanvas" width="200" height="200" style="height:200px; width:200px; posit...

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html

'The width attribute defaults to 300, and the height attribute defaults to 150.' So it does not have the size you want unless you specify if.

FIDDLE: http://jsfiddle.net/RgGJh/2/

Upvotes: 3

Related Questions