Can you combine multiple images into a single one using JavaScript?

后端 未结 3 988
死守一世寂寞
死守一世寂寞 2020-12-01 07:14

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be

3条回答
  •  情书的邮戳
    2020-12-01 07:48

    MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:

    Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
    

    image1:

    image2:

    image3:

    Result:

    Runnable Example:

    var canvas = document.getElementById("canvas");
    image1 = new MarvinImage();
    image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
    image2 = new MarvinImage();
    image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
    image3 = new MarvinImage();
    image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
    
    var loaded=0;
    
    function imageLoaded(){
      if(++loaded == 3){
        var image = new MarvinImage(image1.getWidth(), image1.getHeight());
        Marvin.combineByAlpha(image1, image2, image, 0, 0);
        Marvin.combineByAlpha(image, image3, image, 190, 120);
        image.draw(canvas);
      }
    }
    
    

提交回复
热议问题