Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 canvas is not showing full image

My image size is 940 * 300 but html5 canvas showing only part of image in chrome. Can you please help how to fix this?

Below is the code

<!DOCTYPE html>
<html>
    <head>
        <style></style>
    </head>
    <body onload="draw();">
        <p>Drag me</p>
        <canvas id="paint_area"></canvas>

        <script>
            function draw() {
                var ctx = document.getElementById('paint_area').getContext('2d');

                //ctx.fillStyle = '#cc3300';

                var img_buffer = document.createElement('img');
                img_buffer.src = 'http://www.jobcons.in/homebanner.jpg';
                var imgWidth = img_buffer.width;
                var imgHeight = img_buffer.height;
                ctx.width = imgWidth;
                ctx.height = imgHeight;
                ctx.drawImage(img_buffer,0,0,imgWidth,imgHeight);
            }
        </script>
    </body>
</html>
like image 657
dharani Avatar asked Aug 19 '11 16:08

dharani


People also ask

How do you make a full picture on canvas?

The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.

How do I make my canvas fit the screen in HTML?

Set the Size with CSSto set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.


1 Answers

Two things:

  • You were setting the context's size which doesn't make much sense. The canvas has a width and a height.

  • You should really use img_buffer.onload to make sure you only paint the image when it's loaded and not before it's completely loaded.

Fiddle: http://jsfiddle.net/pimvdb/TpFQ8/

So:

<canvas id="paint_area" width="940" height="300"></canvas>

and:

var cv  = document.getElementById('paint_area'),
    ctx = ctx.getContext('2d');

and:

img_buffer.onload = function() {
    var imgWidth = img_buffer.width;
    var imgHeight = img_buffer.height;
    cv.width = imgWidth;
    cv.height = imgHeight;
    ctx.drawImage(img_buffer, 0, 0, imgWidth, imgHeight);
}
like image 89
pimvdb Avatar answered Sep 20 '22 18:09

pimvdb