Skip to content Skip to sidebar Skip to footer

Html5 Canvas: Image Resizing

I'm trying to place an image on a canvas without resizing it. I thought drawImage(img, x, y) would do the trick, but it stretches the image to fill the canvas. Also supplying drawI

Solution 1:

Don't use CSS to size your canvas. That creates a default sized canvas and stretches it. Set the canvas dimensions directly on it and you'll get a 1 to 1 pixel drawing space.

<canvas id="story" width="800" height="600" style="position:relative;"></canvas>

Solution 2:

Trochoid is right, the style attribute on your canvas tag is causing problems. You could set it in the HTML, as he suggests, or better yet you can leave it blank and set it dynamically in the JS:

<canvasid="story"></canvas><scripttype="text/javascript">window.onload = function() {
      var canvas = document.getElementById("story");
      var context = canvas.getContext("2d");
      var img = document.getElementById("img1");
      var width = parseInt(img.width);
      var height = parseInt(img.height);

      canvas.height=height;
      canvas.width=width;
      context.drawImage(img, 0, 0);
}

</script><imgid="img1"alt=""src="http://link to image"/>

Solution 3:

Also make sure you get the width and height of the image and draw it AFTER it has been loaded.

img.onload = function () {
  var width = parseInt(img.width);
  var height = parseInt(img.height);
  context.drawImage(img, 0, 0, width, height);
};

Solution 4:

You have to first load the function image perfectly before rendering on the screen to do that follow the below code..

<imgid="demo-img"src="image_name.png"><br><canvasid="myCanvas"width="500"height="500"style="border:1px solid #d3d3d3">Your browser does not support the HTML5 canvas tag
</canvas><script>var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("demo-img");
    img.onload=functionfun(){ctx.drawImage(img,0,0,img.width,img.height,0,0,img.width,img.height)}
 </script>

Solution 5:

Try using this library I recently created which can load an image, resize it fixed width & height or precentage, convert to and from other formats like base64 or blob, and allows you to apply a watermark.

varCanvaWork = newCanvaWork();

CanvaWork.loadImage("yourimage.png", function(obj){
    console.log(obj.canvas);  // The usable canvasconsole.log(obj.width);
    console.log(obj.height);
    console.log(obj.image); // Contains the image file
});

https://github.com/vnbenny/canvawork.js

Hope this helps you!

Post a Comment for "Html5 Canvas: Image Resizing"