将图像放在html画布中

时间:2014-06-04 01:04:29

标签: javascript html5 canvas

我不想/想知道如何隐藏html中的图像,而只是通过javascript将它们放在画布中。我现在在做的是:

     

然后在身体中:

<script language="javascript" type="text/javascript">
                var c = document.getElementById("gameCanvas");
                var ctx = c.getContext("2d");
                var img = document.getElementById("cerealBox");
                ctx.drawImage(img,400,200)

            </script>

我试图将图像放在画布上,但还没有找到方法,我只是向W3Schools学习。

3 个答案:

答案 0 :(得分:2)

这是一个快速演示here

var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");

var img = new Image();
img.src = "http://img2.wikia.nocookie.net/__cb20081209142622/fantendo/images/e/e6/Super_8_Bit_Mario.png";

img.onload = function () {
    ctx.drawImage(img, 50, 50, 800, 600, 50, 50, 100, 60);
}

答案 1 :(得分:1)

<强> HTML

<canvas id="gameCanvas"></canvas>

<强> CSS

#gameCanvas { 
    border: 1px solid white; 
    width: 400px; 
}

<强> JS

var canvas = document.getElementById('gameCanvas'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/cerealBox.png';
  base_image.onload = function(){
    context.drawImage(base_image, 400, 200);
  }
}

答案 2 :(得分:0)

HTML

 <img id="myImage" src=""></img>

JavaScript的:

 var imgEl = document.getElementById("myImage");
 imgEl.setAttribute("src", "/Images/MyImages/Album1/myPic.jpg");