canvas 双缓冲 缓冲层有图像 显示不到 展示层

新手上路,请多包涵

问题描述

canvas 双缓冲 缓冲层有图像 显示不到 展示层
在tempCanvas上面有图像
使用 document.body.appendChild(tempCanvas);
放在dom层可以看到 正常显示但是 通过 展示层canvas使用drawImage
显示空白 展示层显示图片啥都是正常的,就是无法显示缓冲层

问题出现的环境背景及自己尝试过哪些方法

谷歌浏览器

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <canvas id="canvas" width="1786" height="850.5"></canvas>
</div>
<script>
    window.onload = () => {

        function initCanvas() {
            const canvas = document.querySelector('#canvas');
            const ctx = canvas.getContext('2d');

            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;

            return {canvas: canvas, ctx: ctx, tempCanvas: tempCanvas, tempCtx: tempCtx};
        }


        function draw() {
            const {canvas, ctx, tempCanvas, tempCtx} = initCanvas();

            const scale = 1 / 6;

            // 重置canvas;
            tempCtx.clearRect(0, 0, tempCanvas.width, tempCanvas.height);

            // 机场平面
            const airport = new Image();
            airport.src = './images/canvas/airport.jpg';

            airport.onload = () => {
                tempCtx.save();
                tempCtx.scale(scale, scale);
                tempCtx.drawImage(airport, 0, 0);
                tempCtx.restore();
            };

            // 飞机位置
            /*const airplane = new Image();
            airplane.src = './images/canvas/airplane-yellow.png';

            airplane.onload = () => {
                tempCtx.drawImage(airplane, 300, 300);
            };*/

            document.body.appendChild(tempCanvas);

            // 重置canvas;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(tempCanvas, 0, 0);
        }

        draw();
    }
</script>
</body>
</html>

你期待的结果是什么?实际看到的错误信息又是什么?

期待显示,没有报错

阅读 3.3k
2 个回答

你的展示层指的是 canvas?如果是的话,因为 ctx.draw(tempCanvas, 0, 0) 的时候,tempCanvas 还没有绘制,它的绘制是等到 image.onload 之后。
改成这样:

airport.onload = () => {
    tempCtx.save();
    tempCtx.scale(scale, scale);
    tempCtx.drawImage(airport, 0, 0);
    tempCtx.restore();

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(tempCanvas, 0, 0);
};
// 重置canvas;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(tempCanvas, 0, 0);

放到 onload 事件中去

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题