【问题标题】:Javascript crop and scale image to be 300 pixelJavascript 将图像裁剪和缩放为 300 像素
【发布时间】:2022-11-18 03:37:00
【问题描述】:

我想知道我们如何在 Javascript 中缩放和裁剪图像。我想将它缩小到 300x300px 并稍微裁剪一下。 你有什么建议吗 ?我有以下代码:

function cropImage(imagePath, newX, newY, newWidth, newHeight) {
//create an image object from the path
var img = document.createElement('img');
img.src = "data:image/png;base64,"+imagePath;
    
//alert(img.width);
//alert(img.height);
//initialize the canvas object
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');



    //set the canvas size to the new width and height
    canvas.width = 300;
    canvas.height = 300;
     
    //draw the image
    
        ctx.drawImage(img, newX, 75, 300, 300, 0, 0, 300, 300);
    variables.imageCrop = canvas.toDataURL();}

谢谢 !

【问题讨论】:

  • imagePath 是一个 url?

标签: javascript image scale crop


【解决方案1】:

我不确定你的 imagePath 是 URL 还是 base64 字符串,但这一行似乎不正确 img.src = "data:image/png;base64,"+imagePath; 相反,你可以将图像路径作为 img.src = imagePath 插入 src 中。

试试看:

function cropImage(imagePath, newX, newY, newWidth, newHeight) {
  const img = document.createElement('img');
  img.src = imagePath;

  const canvas = document.createElement('canvas');
  document.body.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  img.addEventListener('load', function() { //Image needs to be loaded from url

    canvas.width = newWidth;
    canvas.height = newHeight;

    //After loading the image we can draw the new image with the desire size
    ctx.drawImage(img, newX, newY, newWidth, newHeight, 0, 0, newWidth, newHeight);
  });
}

const img = "https://www.google.de/images/srpr/logo11w.png";

cropImage(img, 0, 0, 300, 300);

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 2012-07-21
    • 2015-04-20
    • 1970-01-01
    • 2011-11-16
    • 2016-08-29
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多