Html5 canvas does not show full image

The size of my image is 940 * 300, but the html5 canvas shows only part of the image in chrome. Could you help 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> 
+6
source share
2 answers

Two things:

  • You set a context size that doesn't make much sense. The canvas has a width and a height.

  • You really should use img_buffer.onload to make sure that you only draw the image when it is downloaded, and not before it is fully 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); } 
+10
source

The reason is that you cannot do

  ctx.width= imgWidth; ctx.height=imgHeight; 

You have to do

  can.width= imgWidth; can.height=imgHeight; 

Where can is a link to the canvas, not a canvas context.

Working example:

http://jsfiddle.net/rbNzb/

+6
source

Source: https://habr.com/ru/post/895432/


All Articles