簡體   English   中英

HTML5畫布:圖像大小調整

[英]HTML5 canvas: image resizing

我試圖在沒有調整大小的情況下將圖像放在畫布上。 我認為drawImage(img,x,y)可以做到這一點,但它會拉伸圖像以填充畫布。 同時提供drawImage(img,x,y,width,height)和我的圖像尺寸似乎不起作用。

這是我的代碼:

<canvas id="story" style="position:relative; width:800px; height:600px;"></canvas>

<script type="text/javascript">

window.onload = function() {
  var canvas = document.getElementById("story");
  var context = canvas.getContext("2d");
  var img = document.getElementById("img1");
  var width = parseInt(img.width);
  var height = parseInt(img.height);
  context.drawImage(img, 0, 0, width, height);
}

</script>
<img id="img1" alt="" src="http://link to image"/>

提前致謝!

PS:我添加了parseInt以確保drawImage獲得有效值。

不要使用CSS來調整畫布大小。 這會創建一個默認大小的畫布並將其拉伸。 直接在其上設置畫布尺寸,您將獲得1到1像素的繪圖空間。

<canvas id="story" width="800" height="600" style="position:relative;"></canvas>

Trochoid是正確的,canvas標簽上的style屬性會導致問題。 你可以像他建議的那樣在HTML中設置它,或者更好的是你可以把它留空並在JS中動態設置它:

<canvas id="story"></canvas>

<script type="text/javascript">

window.onload = function() {
      var canvas = document.getElementById("story");
      var context = canvas.getContext("2d");
      var img = document.getElementById("img1");
      var width = parseInt(img.width);
      var height = parseInt(img.height);

      canvas.height=height;
      canvas.width=width;
      context.drawImage(img, 0, 0);
}

</script>
<img id="img1" alt="" src="http://link to image"/>

還要確保獲得圖像的寬度和高度,並在加載后繪制它。

img.onload = function () {
  var width = parseInt(img.width);
  var height = parseInt(img.height);
  context.drawImage(img, 0, 0, width, height);
};

您必須先在屏幕上渲染之前完全加載功能圖像,然后按照以下代碼進行操作。

<img id="demo-img" src="image_name.png">

<br>

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3">Your browser does not support the HTML5 canvas tag
</canvas>

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("demo-img");
    img.onload=function fun(){ctx.drawImage(img,0,0,img.width,img.height,0,0,img.width,img.height)}
 </script> 

嘗試使用我最近創建的這個庫,它可以加載圖像,調整固定的寬度和高度或百分比,轉換為其他格式,如base64或blob,並允許您應用水印。

var CanvaWork = new CanvaWork();

CanvaWork.loadImage("yourimage.png", function(obj){
    console.log(obj.canvas);  // The usable canvas
    console.log(obj.width);
    console.log(obj.height);
    console.log(obj.image); // Contains the image file
});

https://github.com/vnbenny/canvawork.js

希望這對你有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM