简体   繁体   English

如何调整画布上居中的图像的尺寸?

[英]How to resize a centered image on a canvas?

The code I have below will take an uploaded image and center it on a canvas, it is working but I'm unable to change the size of the actual image. 我下面的代码将获取上载的图像并将其放在画布上居中,它可以正常工作,但是我无法更改实际图像的大小。 I want to be able to upload an image and then scale it down by a percentage or pixel with it centered. 我希望能够上传图像,然后将其居中缩小一个百分比或一个像素。

The way it works right now is you upload an image and it automatically gets populated on the canvas. 现在,它的工作方式是上传图像,并且图像会自动填充在画布上。 The final product will return a base64 string that I will convert using C#. 最终产品将返回我将使用C#转换的base64字符串。

Any help would be great, thanks. 任何帮助将是巨大的,谢谢。

Codepen Link Codepen链接

HTML: HTML:

<input type="file">

Javascript: 使用Javascript:

$("input").on("change", function(e) {
  var file = this.files[0];
  if (!file) return;
  var fileReader = new FileReader();
  fileReader.onload = () => {
    var image = new Image();
    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext("2d");

      // Change Background
      context.beginPath();
      context.rect(0, 0, 1000, 1000);
      context.fillStyle = "#7D8491";
      context.fill();

      // Draw Logo      
      context.drawImage(image, canvas.width / 2 - image.width / 2,
        canvas.height / 2 - image.height / 2);

      // Append to body
      $("body").append(canvas);

      // Open base64 url
      //window.open(canvas.toDataURL("image/png"));
    };
    image.src = fileReader.result;
  };
  fileReader.readAsDataURL(file);
  var canvas = document.createElement("canvas");
});

I simply had to divide both the position and the actual width/height by the percentage I wanted to scale the image down. 我只需要将位置和实际的宽度/高度除以要缩小图像的百分比即可。

// Draw Logo      
context.drawImage(
    image, 
    canvas.width / 2 - image.width * .75 / 2,
    canvas.height / 2 - image.height * .75 / 2,
    image.width * .75, image.height * .75
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM