画布响应文本

时间:2017-07-14 12:59:13

标签: javascript canvas

我正在尝试制作响应式帆布游戏(使用找到的代码here来保持宽度高度100%)。为了获得文本响应,我正在使用大众的大小。问题是,即使我在调整大小时调用绘图函数,JavaScript似乎仍然从原始大小获取大众维度。(虽然重新加载页面确实正确调整大小)。

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

1 个答案:

答案 0 :(得分:2)

Canvas不支持css vw 单位。

所以,你应该使用......

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

而不是......

ctx.font = "2vw Arial";

以下是working demo on jsFiddle