【问题标题】:Canvas responsive text画布响应文本
【发布时间】:2017-07-14 21:22:20
【问题描述】:

我正在尝试制作一个响应式画布游戏(使用找到的一些代码 here 保持宽度高度为 100%)。为了使文本具有响应性,我使用 VW 作为尺寸。问题是,即使我在调整大小时调用绘图函数,JavaScript 似乎仍然从原始大小获取 VW 尺寸。(尽管重新加载页面确实正确调整了它的大小)。

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Game</title>

    <style>
        html body{
            margin:0;
            padding:0;
            border:0;
        }
        #canvas{
            display:block;
            background-color: rgb(102,0,102);
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    //change canvas size
    function canvasSize(){
        canvas.style.width = window.innerWidth + 'px';
        canvas.style.height = window.innerHeight + 'px';
        canvas.width = window.innerWidth * window.devicePixelRatio;
        canvas.height = window.innerHeight * window.devicePixelRatio;
        ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }

    //draw function
    function mainDraw(){
        //changing coordinate x,y to centre of canvas
        ctx.translate(canvas.width/2,canvas.height/2);

        //drawing text;
        ctx.font = "2vw Arial";
        ctx.textAlign="center";
        ctx.fillText("RoundCloud Christmas adventure",0,0);

        // draw circle
        ctx.beginPath();
        ctx.arc(0,0,canvas.width / 100,0,Math.PI*2);
        ctx.closePath();
        ctx.fill();
    }

    window.onload = function(){
        canvasSize();
        mainDraw();
        window.addEventListener('resize', canvasSize);
        window.addEventListener('resize', mainDraw);
    }
</script>
</body>
</html>

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    Canvas 不支持 css vw 单位。

    所以,你应该使用 ...

    ctx.font = 2 * window.innerWidth + "px Arial";
    

    而不是...

    ctx.font = "2vw Arial";
    

    这里是working demo on jsFiddle

    【讨论】:

    • 欢迎!
    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 2013-06-23
    • 2021-12-15
    • 2016-04-26
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多