drawImage()用错误的坐标画布

时间:2015-06-04 12:31:44

标签: javascript html canvas

我有一个问题: 我正在使用地图生成器,使用html画布,用户输入图像的X,Y,宽度和高度。 但是当我使用带有用户输入的drawImage时,图像不适合Canvas XY以及选择的高度和宽度(以像素为单位)。有什么我可以用来解决这个问题吗?

<html lang=''>
<head>
   <title>Map tools</title>
</head>
<body>
    <div align='center'>
        <canvas id='map' class='mapcanvas' width="800" height="400">
        </canvas>
        <p><a href="#" onclick="loadXml()" class="submitbutton">Send</a></p>
        <textarea id="xmlinput" class="inputTextArea" placeholder="coords"></textarea>
    </div>
</body>
<script>
function loadXml(){
co = document.getElementById("xmlinput").value.split(',') // X, Y, H, L
canvas = document.getElementById("map");
context = canvas.getContext("2d");
ground.src = 'http://i.imgur.com/Z3DyMAM.png'
ground.onload = function (){
context.drawImage(ground, co[0], co[1], co[2], co[3]);
}
}
</script>
</html>

2 个答案:

答案 0 :(得分:1)

地面未定义。我已经把它放进去了。

<html lang=''>
<head>
   <title>Map tools</title>
</head>
<body>
    <div align='center'>
        <canvas id='map' class='mapcanvas' width="800" height="400">
        </canvas>
        <p><a href="#" onclick="loadXml()" class="submitbutton">Send</a></p>
        <textarea id="xmlinput" class="inputTextArea" placeholder="coords"></textarea>
			<img id='ground' style='display: none' /> <!--You forgot the image!-->
    </div>
</body>
<script>
function loadXml(){
  var co = document.getElementById("xmlinput").value.split(','), // X, Y, H, L
      canvas = document.getElementById("map"),
      context = canvas.getContext("2d"),
      ground = document.getElementById('ground'); //ground was undefined!
  ground.src = 'http://i.imgur.com/Z3DyMAM.png'
  ground.onload = function (){
    context.drawImage(ground, co[0], co[1], co[2], co[3]);
  }
}
</script>
</html>

答案 1 :(得分:1)

您的代码完美无缺。只需将其添加到页面(创建图像对象)

     <!DOCTYPE html />
    <html lang=''>
    <head>
       <title>Map tools</title>
    </head>
    <body>
        <div align='center'>
            <canvas id='map' class='mapcanvas' width="800" height="400">
            </canvas>
            <p><a href="#" onclick="loadXml()" class="submitbutton">Send</a></p>
            <textarea id="xmlinput" class="inputTextArea" placeholder="coords"></textarea>
        </div>
    </body>
    <script>
    function loadXml(){
    co = document.getElementById("xmlinput").value.split(',') // X, Y, H, L
    canvas = document.getElementById("map");
    context = canvas.getContext("2d");
var ground=new Image();
    ground.src = 'http://i.imgur.com/Z3DyMAM.png'
    ground.onload = function (){
    context.drawImage(ground, co[0], co[1], co[2], co[3]);
    }
    }
    </script>
    </html>