简体   繁体   中英

Canvas doesn't follow up resize of image?

I've got the following piece of code:

HTML

<img src="http://hollywoodteenonline.com/wp-content/uploads/2011/12/justin_bieber_someday_fragrance_dree_hemingway.jpg" id="imagem"/>

<canvas id="mycanvas">

CSS

#mycanvas{
  height:200px;
  width: 200px;
  border: solid;
  color: black;
}

#imagem{
  height:200px;
  width: 200px;
}

Javascript

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

ctx.drawImage(img,0,0);

As you can see, the canvas doens't follow up the resize of the original image. As the code is written it "should" show all of the source but resized to de designated canvas. Is there any way to go around this?

Issues

First issue is that you don't set a size for your canvas element by using its properties. This is the only way you can affect the content of the canvas and not settings it means it will default to 300 x 150 pixel no matter what you set as CSS rule for it.

Second issue is that you are using CSS to the set size. This will affect the element itself, not the content of the canvas. Technically this isn't wrong in case you want to scale the canvas as an image, but it won't do anything for the canvas and the result is that you just scale the 300x150 pixels around.

The third issue, if the image is of different size than 300x150 it won't fit the canvas (too small or get cropped if too big).

Solutions

One solution is to set the size of the canvas to the size of the image and paint the image in:

canvas.width  = img.width;
canvas.height = img.height;

ctx.drawImage(img, 0, 0);

Now you can resize the canvas (as an image using CSS) if you want.

Or you can scale the image using the size of the canvas (remove the CSS rule; and you still need to set a size for canvas):

ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

LIVE DEMO HERE

You also need to take care in how you invoke your script. For images to work with canvas they need to be loaded. As they load asynchronous you need to handle load events one way or another (ie. inside a window.onload in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM