1. 程式人生 > >js設定圖片不拉伸

js設定圖片不拉伸

設定圖片不拉伸的js:

/** * 設定圖片大小並且不拉伸 * @param ImgD * @param width * @param height * @constructor */
function DrawImage(ImgD, width, height) {
    var image = new Image();
    image.src = ImgD.src;
    if (image.width > 0 && image.height > 0) {
        if (image.width / image.height >= width / height) {
            if (image.width > width) {
                ImgD.width = width;
                ImgD.height = (image.height * width) / image.width;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
            ImgD.alt = image.width + "x" + image.height;
        } else {
            if (image.height > height) {
                ImgD.height = height;
                ImgD.width = (image.width * height) / image.height;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
            ImgD.alt = image.width + "x" + image.height;
        }
    }
}