HTML5 blend two images while the one is moving

104 views Asked by At

I have a code with two pictures,the backround picture and a smaller one that's moving random around the canvas. The small picture must be blended (without global alpha) while is moving.Do you have any idea? Here is what I did so far.

 <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

There are 1 answers

10
Sam Greenhalgh On BEST ANSWER

I'm a little confused about what you're expecting to happen. Perhaps this is what you're trying to do?

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/