在画布上随机显示图像

时间:2012-04-27 09:51:45

标签: javascript image canvas

我需要帮助才能使用Javascript和HTML5对此进行编码。请指教!

<HTML>
<HEAD>
<SCRIPT language="javascript">
    function Add() {
        if (document.getElementById('amount').value < 100){
            document.getElementById('amount').value++;
            newIMG = document.createElement("IMG");
            newIMG.src = 'jef-frog.gif';
            newIMG.width = 50;
            newIMG.height = 50;
            document.getElementById("imagedest").appendChild(newIMG);
        }
    }

    function Remove() {
        if(document.getElementById('amount').value > 0)
            document.getElementById('amount').value--;
        imagedest.removeChild(imagedest.lastChild);
    }

    function numeralsOnly(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
            ((evt.which) ? evt.which : 0));
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
</SCRIPT>
</HEAD>

<BODY>
    <H2>TESTING</H2>
    PREY
    <BR/>
    <img src="jef-frog.gif" alt="frogsonice.com" width="100" height="100"/>

<BR/>
<FORM>
    <INPUT type="button" value="+" onClick="Add()"> 
    <input type="text" id="amount" value=0  maxlength="3" size="1" onkeypress="return numeralsOnly(event)">
    <INPUT type="button" value="-" onClick="Remove()">

    <div id='imagedest'>
    </div>

</FORM>
</BODY>
</HTML>

我测试了代码,它会显示在<div>标记中,但我想让它出现在上面创建的画布中。我不知道如何捕捉画布中的东西。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您需要使用canvas api在其上绘制内容

有形状的示例

<html>  
 <head>  
  <script type="application/javascript">  
    function draw() {  
      var canvas = document.getElementById("canvas");  
      if (canvas.getContext) {  
        var ctx = canvas.getContext("2d");  

        ctx.fillStyle = "rgb(200,0,0)";  
        ctx.fillRect (10, 10, 55, 50);  

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
        ctx.fillRect (30, 30, 55, 50);  
      }  
    }  
  </script>  
 </head>  
 <body onload="draw();">  
   <canvas id="canvas" width="150" height="150"></canvas>  
 </body>  
</html>