Using drawImage () to output fixed size images to canvas?

How to use drawImage()to output full-size images to the canvas, 300px X 380pxregardless of the size of the original image?

Example:

1). If there is an image 75px X 95px, I want to be able to draw it in accordance with the canvas 300px X 380px.

2). If there is an image 1500px X 1900px, I want to be able to draw it in accordance with the canvas 300px X 380px.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("myPic");
ctx.drawImage(img,10,10);

What options are there to prevent quality loss?

+4
source share
2 answers

, :

var ratioX = canvas.width / image.naturalWidth;
var ratioY = canvas.height / image.naturalHeight;
var ratio = Math.min(ratioX, ratioY);

ctx.drawImage(image, 0, 0, image.naturalWidth * ratio, image.naturalHeight * ratio);

; 300x380 , .

. DPI (, PPI). , 300x380 (, , , ..).

:

PDF PPI 300, 3 x 3,8 ( ), :

var w = (3 / 2.54) * 300;   // cm -> inch x PPI
var h = (3.8 / 2.54) * 300;

canvas, CSS:

canvas.width = w|0;             // actual bitmap size, |0 cuts fractions
canvas.height = h|0;
canvas.style.width = "300px";   // size in pixel for screen use
canvas.style.height = "380px";

PDF, PDF ( , ).

, , , , .

+6

. , .

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var x = 188;
      var y = 30;
      var width = 200;
      var height = 137;
      var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, x, y, width, height);
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
    </script>
  </body>
</html>

: http://www.html5canvastutorials.com/tutorials/html5-canvas-image-size/

+1

All Articles