使用双缓冲在画布上绘制图像时,无法获得完整图像吗?

时间:2019-02-20 03:16:40

标签: javascript html html5-canvas drawimage html5boilerplate

这是我的代码,我使用两个画布绘制图像以避免闪烁,但是使用这种方法时我无法获得完整图像,有人可以帮忙吗? 如果我只使用一个画布,则图像显示效果很好,看来Javascript创建的secondarycanvas在显示图像时遇到了问题,但我找不到问题所在。任何帮助表示赞赏!

<!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>

1 个答案:

答案 0 :(得分:0)

我将secondaryCanvas.weight=c.weight;更改为secondaryCanvas.width=c.width;,您的代码似乎可以正常工作了。

<!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>