gpt4 book ai didi

Javascript:固定大小 Canvas 中的可变大小图像

转载 作者:行者123 更新时间:2023-12-02 13:49:15 26 4
gpt4 key购买 nike

我有一个固定的 HTML5 Canvas ,尺寸为 300x300。我正在通过 Javascript 调整页面上其他图像的大小,使其最大宽度/高度为 300 像素(取决于哪个尺寸较大)。

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

有没有办法:

  1. 使用 Javascript 调整这些图像的大小,以便它们以最大高度或宽度 300 像素绘制到 Canvas 上。

并且

  • 是否让 Canvas 保留其 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);
    }
    }

    最佳答案

    我已经创建了尝试匹配上面解释的场景的 fiddle 。

    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/

    关于Javascript:固定大小 Canvas 中的可变大小图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132462/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com