【问题标题】:How to resize the content on canvas?如何调整画布上的内容大小?
【发布时间】:2014-12-09 16:33:45
【问题描述】:

我创建了一个画布,但是当我调整窗口大小时,画布内容消失了。我正在使用以下代码。所以画布和背景图像的原始尺寸是960x558。我正在使用那些 app.stage.canvas 的宽度和高度,因为画布和背景图像在调整大小时变得不同。

function resize(){
        app.stage.canvas.width = $('#canvas').parent().width();
        //app.stage.canvas.height = window.innerHeight;
        app.stagetools.canvas.width = $('#canvas').parent().width();


        //tools container
        if(app.stage.canvas.width < 960){
            app.stage.canvas.height = '558';
        }

        if(app.stage.canvas.width < 739){
            app.stage.canvas.height = '400';
        }

        if(app.stage.canvas.width < 510){
            app.stage.canvas.height = '300';
        }

        if(app.stage.canvas.width < 450){
            app.stage.canvas.height = '240';
            tools.toolsScale = 0.7;
        }

        tools.toolsContainer.scaleX = tools.toolsScale;
        tools.toolsContainer.scaleY = tools.toolsScale;
        tools.toolsContainer.x = app.stagetools.canvas.width/2 - 150 * tools.toolsScale;



        app.container.x = app.stage.canvas.width/2;
        app.container.y = app.stage.canvas.height/2;

        //background image      
        app.bgscale = app.stage.canvas.width /  app.backgroundBounds.width;

        if(app.backgroundBounds.height * app.bgscale > app.stage.canvas.height){
           app.bgscale = app.stage.canvas.height /  app.backgroundBounds.height;
        }

        app.backgroundContainer.scaleX = app.bgscale;
        app.backgroundContainer.scaleY = app.bgscale;


        app.backgroundContainer.x = Math.floor(app.stage.canvas.width/2 - app.backgroundBounds.width/2 * app.bgscale);
        app.backgroundContainer.y = Math.floor(app.stage.canvas.height/2 - app.backgroundBounds.height/2 * app.bgscale);


        tools.clearHandler();

        app.stage.update();
        app.stagetools.update();

    }

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    这是意料之中的。调整画布大小时,其内容被清除。

    来自standard

    当用户代理要将位图尺寸设置为宽度和高度时, 它必须运行以下步骤:
    ...
    3. 将暂存位图调整为新的宽度和高度,并将其清除为完全透明的黑色。
    4. 如果渲染上下文有输出位图,并且暂存位图与输出位图是不同的位图,则将输出位图调整为新的宽度和高度,并将其清除为完全透明的黑色。

    要解决这个问题,您必须监听窗口对象的 resize 事件并在调用时重绘所有内容:

    window.addEventListener("resize", function() {
        // call redraw method here...
    }, false);
    

    希望这会有所帮助。

    【讨论】:

    • 这个重绘方法看起来怎么样?
    • @zoolle 由您来定义(无论您需要重绘什么)
    猜你喜欢
    • 2022-01-15
    • 2014-07-23
    • 2014-06-27
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多