merging canvas and background

前端 未结 2 475
萌比男神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条回答
  • 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
    <img id='bk' src="graphics/teethDrawing.gif" 
         width="705" style="position: absolute; z-index: -1" />
    
    // 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);
    
    0 讨论(0)
  • 2021-01-23 10:40

    Would you like the drawing to have height/width and position:absolute style tags? You can then send those style tags to your database so that other visitors can see the positioning of the drawing on top of the z-index:-1 image.

    <img src="drawing.jpg" style="position:absolute;left:50px;top:120px;" />
    
    0 讨论(0)
提交回复
热议问题