簡體   English   中英

Javascript:固定大小畫布中的可變大小圖像

[英]Javascript: Variable-sized image in fixed-sized canvas

我有一個尺寸為300x300的固定HTML5畫布。 我正在通過Javascript重新調整頁面上其他圖像的大小,使其最大寬度/高度為300px(取決於較大的尺寸)。

但是,這實際上並沒有調整源圖像的大小,並且當我在畫布上繪制它們時,將使用原始大小。

有沒有辦法:

  1. 使用Javascript調整這些圖像的大小,以便將它們繪制到最大高度或寬度為300px的畫布上。

  1. 畫布是否保留其300x300尺寸並在其中放置了調整大小的圖像,以便創建一個300x300的正方形,其中完全包含可變大小的圖像?

(請考慮制作一個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);
              }
            }

我創建了試圖匹配上述情況的小提琴。

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM