merging canvas and background

前端 未结 2 474
萌比男神i
萌比男神i 2021-01-23 10:00

I have a canvas that has a GIF background. I need for the user to upload the drawing and the BG, so another user can see where the drawing is in relation to the BG. The canvas.

2条回答
  •  梦毁少年i
    2021-01-23 10:29

    You can add your background image "behind" the existing canvas drawings using compositing.

    // give the image an id so it's more easily fetched
    
    
    // fetch a reference to the bk image
    var bk=document.getElementById('bk');
    
    // causes new drawings to be drawn behind existing drawings
    ctx.globalCompositeOperation='destination-over';
    
    // draw the img to the canvas (behind existing lines)
    ctx.drawImage(bk,0,0);
    
    // always clean up! Reset to default.
    ctx.globalCompositeOperation='source-over';
    

    This process will permanently add the bk image to the canvas. If you need the bk and canvas-drawings separated then you can create a second in-memory canvas to flatten your content by drawing both the bk-image and your canvas-drawings to the in-memory canvas.

    // create a temporary canvas 
    var mem=document.createElement('canvas');
    var mctx=mem.getContext('2d');
    mem.width=canvas.width;
    mem.height=canvas.height;
    
    // draw the bk to the mem canvas
    mctx.drawImage(bk,0,0);
    
    // draw the main canvas to the mem canvas
    mctx.drawImage(canvas,0,0);
    

提交回复
热议问题