Javascript:固定大小的画布

时间:2016-12-13 23:40:27

标签: javascript html html5 canvas image-scaling

我有一个固定的HTML5画布,尺寸为300x300。我正在调整页面上的其他图像,以通过Javascript获得最大宽度/高度300px(取决于哪个尺寸更大)。

但实际上并没有调整源图像的大小,当我在画布上绘制它们时,会使用原始大小。

有办法:

  1. 使用Javascript调整这些图像的大小,以便将它们绘制到画布上,最大高度或宽度为300px。
    1. 画布是否保留了300x300的尺寸,并在其内部调整了大小调整后的图像,以便创建一个300x300的正方形,其中包含可变尺寸的图像?
    2. (想想制作一个300x300的Photoshop文件,你放入各种图像并调整大小以适应)

      这是否可以使用Javascript / canvas?

      修改

      以下是我根据接受的答案最终使用的代码:

      var ssItems = [exampleUrls], //array of image paths
      imgHolder = document.getElementById("img-holder");
      
      for (var i = 0; i < ssItems.length; i++) {
                var img = new Image(),
                  imgSrc = "/ItemImages/Large/" + ssItems[i] + ".jpg",
                  imgW,
                  imgH;
                img.src = imgSrc;
                img.onload = function () {
                    var canvas = document.createElement("canvas"),
                      ctx = canvas.getContext("2d");
                    canvas.setAttribute("class", "img-canvas");
                    canvas.setAttribute("width", "300");
                    canvas.setAttribute("height", "300");
                    imgHolder.appendChild(canvas);
                    imgW = (canvas.height * this.width) / this.height;
                    imgH = (canvas.width * this.height) / this.width;
                    if (this.height > this.width) {
                      ctx.drawImage(this, canvas.width / 2 - imgW / 2, 0, imgW, canvas.height);
                    } else {
                      ctx.drawImage(this, 0, canvas.height / 2 - imgH / 2, canvas.width, imgH);
                    }
                  }
      

1 个答案:

答案 0 :(得分:2)

我创造了试图匹配上述情景的小提琴。

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

var image = new Image();
image.src = 'http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg';

// calculates width and height with respect to canvas
var width = (canvas.height * image.width) / image.height;
var height = (canvas.width * image.height) / image.width;

// takes width or height full choosing the larger value and centers the image
if(image.height > image.width){
  ctx.drawImage(image, canvas.width / 2 - width / 2, 0, width, canvas.height);
}else{
  ctx.drawImage(image, 0, canvas.height / 2 - height / 2, canvas.width, height);
}

您可以查看一下:https://jsfiddle.net/q8qodgmn/1/

相关问题