第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將圖像縮放和居中到正方形尺寸?

如何將圖像縮放和居中到正方形尺寸?

哈士奇WWW 2021-11-12 16:07:41
這些問題很相似,但沒有幫助:this、this、this和this。目標是將圖像繪制到方形畫布上,同時保留原始縱橫比,如果原始縱橫比不是正方形,則將圖像居中。例如,獲取附加的 1262x2688 圖像。下面的代碼將其調(diào)整為 100x100,但它扭曲了縱橫比。代碼應(yīng)該: (1) 縮放圖像以適合 100x100 畫布;(2) 保持縱橫比;(3) 在畫布內(nèi)垂直和水平居中圖像。    // Create canvas element.    var canvas = $(document.createElement("canvas"));    // Get canvas context.    var context = canvas[0].getContext("2d");    // Set canvas size.    canvas[0].width = 100;    canvas[0].height = 100;    // Write image to canvas.    context.drawImage(image, 0, 0, newWidth, newHeight);圖片
查看完整描述

3 回答

?
滄海一幻覺

TA貢獻1824條經(jīng)驗 獲得超5個贊

這是我們使用的代碼:


    // Create canvas element.

    var canvas = $(document.createElement("canvas"));


    // Get canvas context.

    var context = canvas[0].getContext("2d");


    // Set canvas size.

    canvas[0].width = canvasWidth;

    canvas[0].height = canvasHeight;


    // Set image size, must use image.naturalWidth and image.naturalHeight -- not image.width and image.height.

    const imageWidth = image.naturalWidth;

    const imageHeight = image.naturalHeight;


    // Set scale to fit image to canvas, 

    const scale = Math.min(canvasWidth/imageWidth, canvasHeight/imageHeight);


    // Set new image dimensions.

    const scaledWidth = imageWidth * scale;

    const scaledHeight = imageHeight * scale;


    // Draw image in center of canvas.

    context.drawImage(image, (canvasWidth - scaledWidth)/2, (canvasHeight - scaledHeight)/2, scaledWidth, scaledHeight);



查看完整回答
反對 回復(fù) 2021-11-12
?
臨摹微笑

TA貢獻1982條經(jīng)驗 獲得超2個贊

要在保留外觀的同時使圖像適合畫布,請使用以下命令


const w = image.naturalWidth;

const h = image.naturalHeight;


// Get the min scale to fit the image to the canvas

const scale = Math.min(canvas.width / w, canvas.height / h);


// Set the transform to scale the image, and center to the canvas

ctx.setTransform(scale, 0, 0, scale, canvas.width / 2, canvas.height / 2);


// draw the image offset by half its width and height to center and fit

ctx.drawImage(image, -w / 2, -h / 2, w, h);


// to reset the transform

// ctx.setTransform(1,0,0,1,0,0);


查看完整回答
反對 回復(fù) 2021-11-12
?
守著一只汪

TA貢獻1872條經(jīng)驗 獲得超4個贊

假設(shè)我的計算方式正確,以下可能有效?


ratio = image.width/image.height;

if (image.width > image.height) {

    output.height = ( 100 / ratio ) 

    output.width = 100

    output.x = 0

    output.y = (100 - output.height) / 2

} else {

    output.height = 100

    output.width = 100 * ratio

    output.x = (100 - output.width) / 2

    output.y = 0

}


查看完整回答
反對 回復(fù) 2021-11-12
  • 3 回答
  • 0 關(guān)注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號