簡體   English   中英

如何調整畫布上居中的圖像的尺寸?

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

我下面的代碼將獲取上載的圖像並將其放在畫布上居中,它可以正常工作,但是我無法更改實際圖像的大小。 我希望能夠上傳圖像,然后將其居中縮小一個百分比或一個像素。

現在,它的工作方式是上傳圖像,並且圖像會自動填充在畫布上。 最終產品將返回我將使用C#轉換的base64字符串。

任何幫助將是巨大的,謝謝。

Codepen鏈接

HTML:

<input type="file">

使用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");
});

我只需要將位置和實際的寬度/高度除以要縮小圖像的百分比即可。

// 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