javascripthtmlhtml5-canvasdrawimagehtml5boilerplate

when using double buffering to draw image on canvas, cannot get the complete image?


this is my code, i use two canvas to drawimage to avoid flickering, but i cant get the full image when use this way, anyone can help please? if i only use one canvas the image display fine, it seems the secondarycanvas that created by Javascript got some issue to display the image, but i can't find what's wrong. any help is appreciated!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Decorate</title>
</head>
<body>
<div class="content-box">
<canvas id="canvas" width="360" height="740" style="border:1px solid #d3d3d3"></canvas>

</div>
<script>
var c=document.getElementById("canvas");
var ctx = c.getContext("2d");

var secondaryCanvas=document.createElement("canvas");
var secondaryCtx=secondaryCanvas.getContext("2d");
secondaryCanvas.weight=c.weight;
secondaryCanvas.height=c.height;
var bgimg=new Image();
bgimg.src=imageEncoder[24].background;
bgimg.onload=function() {
secondaryCtx.drawImage(bgimg, 0, 0);
ctx.drawImage(secondaryCanvas,0,0);
}
</script>
</body>
</html>

Solution

  • I change secondaryCanvas.weight=c.weight; to secondaryCanvas.width=c.width; and your code seems to work now.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Decorate</title>
    </head>
    <body>
    <div class="content-box">
    <canvas id="canvas" width="360" height="740" style="border:1px solid #d3d3d3"></canvas>
    
    </div>
    <script>
    var c=document.getElementById("canvas");
    var ctx = c.getContext("2d");
    
    var secondaryCanvas=document.createElement("canvas");
    var secondaryCtx=secondaryCanvas.getContext("2d");
    
    secondaryCanvas.width=c.width;
    secondaryCanvas.height=c.height;
    
    
    
    var bgimg=new Image();
    bgimg.src= "https://picsum.photos/360/740"
    bgimg.onload=function() {
    secondaryCtx.drawImage(bgimg, 0, 0);
    ctx.drawImage(secondaryCanvas,0,0);
    }
    </script>
    </body>
    </html>