0

I want this image in my canvas but it is getting stretched and not fitting the box properly. What am I missing?

Here is my code:

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


var img = new Image();
img.src = "my image url";

img.onload = function(){
    ctx.drawImage(img,0,0);   
}

Please check this image: https://i.stack.imgur.com/RMZM2.png

What I want is my logo fit in the canvas box.

Here is my whole logo: https://i.stack.imgur.com/4jFjM.png

user3657517
  • 35
  • 1
  • 9

1 Answers1

0

If you want to your image to fit with in the canvas-

ctx.drawImage(img,0,0,imgWidth,imgHeight,x,y, canvas.width, canvas.height);

where x and y is the top left position where you want to display your logo. imgWidth and imgHeight are the width and height of your logo respectively.

enter image description here

Refer this image. http://www.html5canvastutorials.com/tutorials/html5-canvas-image-crop/

Cheezy Code
  • 1,685
  • 1
  • 14
  • 18
  • tried this: ctx.drawImage(img,0,0,489,200,0,0, canvas.width, canvas.height); – user3657517 Nov 19 '15 at 09:24
  • but it is coming a blank space – user3657517 Nov 19 '15 at 09:24
  • I actually got it working, just facing a small issue. I have used this: ctx.drawImage(img,0,0,canvas.width,canvas.height); But my logo image is coming 300x150 only in any screen size. Can you help me why is it so? – user3657517 Nov 19 '15 at 09:33
  • user3657517 There are only two functions in context. ctx.drawImage(img,x,y) and ctx.drawImage(img, sx, sy, sw,sy, dx,dy,dw,dh); where s is source and d is destination – Cheezy Code Nov 19 '15 at 09:58
  • Instead use - ctx.drawImage(img,0,0,imgwidth,imgheight, 0,0,canvas.width,canvas.height); – Cheezy Code Nov 19 '15 at 10:00
  • when I alert my canvas width which is responsive with this: window.alert(canvas.width); IT IS COMING 300 ONLY IN ALL THE SCREEN RESOLUTION, THAT'S WHY DRAW IMAGE IS TAKING 300 AS WIDTH. – user3657517 Nov 19 '15 at 10:05
  • logo image is displaying in 100% but it is taking 300 as canvas width only so that the image is getting stretched. – user3657517 Nov 19 '15 at 10:12
  • It will be stretched if you want it to fit the width but height remains same. You can do one thing center the logo and fill the canvas with the background color of your image. – Cheezy Code Nov 19 '15 at 10:14
  • I cant do that, I have to make it in full width, height will be ok if not fixed, but even after removing fixed heigh it is taking 300px canvas size only. – user3657517 Nov 19 '15 at 10:58
  • Can you please help me on this: http://stackoverflow.com/questions/33803418/not-able-to-download-final-merged-canvas – user3657517 Nov 19 '15 at 12:03