html / javascript canvas drawImage没有加载2次

问题描述 投票:0回答:2

我想将图像放在HTML5画布中。我找到了一些有效的示例代码,但是当我实际上只需要1个图像时,该图像被加载了2次。我可以使用JavaScript或CSS隐藏其中一个图像,但是我正在寻找一种方法,该图像仅需要加载一次。

<!DOCTYPE html>
<html>
<body>
    <img id="img" src="img.png" width="150px" height="150px">
    <canvas id="canvas" width="200px" height="200px"></canvas>

    <script type="text/javascript">
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var img = document.getElementById("img");
        ctx.drawImage(img, 0, 0);
    </script>
</body>
</html>
javascript html5 canvas html5-canvas
2个回答
3
投票

图像被绘制了两次,因为您首先创建了<img../>节点,然后将其重新绘制到画布上。

只需删除<img id="img" src="img.png" width="150px" height="150px">并将其添加到您的JavaScript代码中:

img = new Image();
img.src = 'img.png';
img.onload = function(){
    ctx.drawImage(img, 0, 0);
}

0
投票

图像被绘制了两次,因为您首先创建了节点,然后将其重新绘制到画布上。但是使用上面的代码图像无法缩放使用以下代码在画布上绘制图像并响应画布]

<div id="worldmap" style="height=100%;width=100%"><canvas id="myStaticMap"></canvas><div>
 var canvas = document.getElementById("myStaticMap"),
                    ctx = canvas.getContext("2d");
canvas.width = $("#worldmap").width();
 canvas.height = $("#worldmap").height();


ctx.drawImage(mapImage, 0, 0, canvas.width, canvas.height);

canvas.height =高度;ctx.drawImage(mapImage,0,0,width,height);

canvas.height =高度;ctx.drawImage(mapImage,0,0,width,height);

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.