簡體   English   中英

html5中的畫布圖像大小

[英]canvas image size in html5

var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.src = document.getElementById("tempImg").src;
imageObj.onload = function () {
    var x = 188;
    var y = 30;
    var width = 200;
    var height = 137;
    context.drawImage(imageObj, x, y, width, height);
    context.font = "20pt Calibri";
    context.fillText(locationtxt, 40, 40);
};
<canvas id="canvasPnl" width="132" height="120" style="border:0px solid #d3d3d3;"></canvas>

圖像的大小變得越來越大,它不適合畫布,也可以旋轉圖像。

如何在畫布中獲取原始圖像?

好的,看看下面的重做代碼。

注意“imageObj.src = document.getElementById(”tempImg“)。src;” 必須追求 imageObj.onload。

我無法訪問您的locationtxt或您的tempImg,因此我認為您確定它們不是您問題的根源。

這行代碼將采用任意大小的圖像,並通過縮放它來強制它適合您指定的畫布大小。 縮放時,如果畫布大小與圖像大小不成比例,則可能會出現圖像失真。

context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);

這是你的代碼 - 只是修改了一下:)

var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.onload = function () {
    context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
    context.font = "20pt Calibri";
    context.fillText(locationtxt, 40, 40);
};
imageObj.src = document.getElementById("tempImg").src;
<html>
<head>
    <title></title>
</head>
<style type="text/css">
#mycanvas
{
border: 1px solid black;
}
</style>
<script type="text/javascript">
window.addEventListener('load', function () {
  var img = new Image, ctx = document.getElementById('myCanvas').getContext('2d');
  var img1=new Image;
  img.src = 'ship.png';
  img1.src='3D025.jpg';
  img.addEventListener('load', function () {
     var width = img.naturalWidth; // this will be 300
  var height = img.naturalHeight; // this will be 400

    var interval = setInterval(function() {
      var x = 260, y = 0;

      return function () {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(img1, 0, y);
        ctx.drawImage(img, x, 300,width,height);

        x += 1;
        if (x > ctx.canvas.width) {
          x = 260;
         width=width-10;
         height=height-10;
         ctx.drawImage(img, x, 300,width,height);
        }
        if (x == 750) {
          x = 260;

        }
      };
    }(), 1000/40);
  }, false);
}, false);

</script>

<body>

<canvas id="myCanvas" height="600" width="1000"></canvas>

</body>
</html>

暫無
暫無

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

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