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

图像的大小变得越来越大,它不适合画布,并且图像也被旋转了。

如何在画布中获取原始图像?

4

2 回答 2

3

Ok, take a look at your reworked code below.

Notice "imageObj.src = document.getElementById("tempImg").src;" must go after imageObj.onload.

I have no access to your locationtxt or your tempImg, so I assume you are sure they are not the source of your problem.

This line of code will take an image of ANY size and force it to fit in your specified canvas size by scaling it. When it scales, you may get image distortion if your canvas size is not proportional to your image size.

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

Here is your code -- just modified a bit :)

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;
于 2013-04-02T06:11:35.630 回答
0
<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>
于 2014-04-15T10:34:26.063 回答