HTML5混合两个图像,而一个正在移动

时间:2014-11-25 19:54:07

标签: html5-canvas blending

我有一张带有两张照片的代码,背景图片和一张在画布周围随机移动的小图片。小图片在移动时必须混合(没有全局alpha)。你有什么想法吗?这是我到目前为止所做的。

 <script type="text/javascript">
    var context;
    var dx= 4;
    var dy=4;
    var y=150;
    var x=10;

    function draw(){
        var imageObj = document.getElementById("night");
        var imageObj2 = document.getElementById("small_image");
        context= myCanvas.getContext('2d');
        context.clearRect(0,0,1920,1200);
        context.drawImage(imageObj, 0, 0);
        context.drawImage(imageObj2, x, y);
        if( x<0 || x>1920-imageObj2.width)
        dx=-dx;
        if( y<0 || y>1200-imageObj2.height)
            dy=-dy;
            x+=dx;
            y+=dy;
        }
    setInterval(draw,10); 
    </script>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>It's Christmas Time</title>
    <style type="text/css">

    </style>
    </head>
    <body>
        <img id="night" src="cartoon.jpg" alt="sima" width="300" height="200" hidden>
        <img id="small_image" src="small_image.gif" hidden>

        <canvas id="myCanvas" width="1920" height="1200"></canvas>


    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

我对你期待发生的事情感到有些困惑。也许这就是你想要做的?

var x = 0,
    y = 0,
    dx = 1,
    dy = 1;

function draw(){
      var imageObj = document.getElementById("night");
      var imageObj2 = document.getElementById("small_image");
      context= myCanvas.getContext('2d');
      context.clearRect(0,0,1920,1200);
      context.drawImage(imageObj, 0, 0);
      context.drawImage(imageObj2, x, y);
      if( x<0 || x > 1920 - imageObj2.width)
          dx = -dx;
      if( y < 0 || y > 1200 -imageObj2.height)
          dy = -dy;
      x += dx;
      y += dy;
}
setInterval(draw,10); 

http://jsfiddle.net/avzn89ay/