【问题标题】:html5 canvas context is blurry in fullpagehtml5画布上下文在整页中模糊
【发布时间】:2019-02-01 18:23:47
【问题描述】:

HTML5 画布显示模糊的上下文。

绿色背景上的红色矩形:

当我制作画布宽度和高度 == 窗口宽度和高度(整页)时。即使body{ margin: 0; },它也会显示一个水平滚动条。我该如何解决这个问题?

我的代码

html->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <canvas></canvas>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="main.js"></script>
</body>
</html>

css ->

body
{
    margin: 0;
}
canvas
{
    /*border: 1px solid black;*/
    background: green;
}

jquery ->

    $(document).ready(function(){

    $.fn.showMSG = function(){

        var canvas = $("canvas");
        var ctx    = canvas[0].getContext("2d");

        canvas.width($(window).width());
        canvas.height($(window).height());

        ctx.fillStyle = "#FF0000";
        ctx.fillRect(0,0,50,50);

    }

    $(window).ready(function(){
        $.fn.showMSG();
    });

});

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    您的代码正在画布上调用.width().height() 方法。这不会改变画布的heightwidth 属性,而是改变它的heightwidth 样式,使其看起来被拉伸。而是使用.attr() 来更改画布的heightwidth 属性。

    请参阅下面的工作示例:

    $(document).ready(function() {
    
      $.fn.showMSG = function() {
    
        var canvas = $("canvas");
        var ctx = canvas[0].getContext("2d");
    
        canvas.attr('width', $(window).width());
        canvas.attr('height', $(window).height());
    
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(0, 0, 50, 50);
    
      }
    
      $(window).ready(function() {
        $.fn.showMSG();
      });
    
    });
    body {
      margin: 0;
      overflow: hidden;
    }
    
    canvas {
      /*border: 1px solid black;*/
      background: green;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <title>Document</title>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body>
    
      <canvas></canvas>
    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="main.js"></script>
    </body>
    
    </html>

    【讨论】:

    • 它可以工作,但是为什么会有一个水平滚动条?
    • @MorshedSaif 请查看我更新的示例(正文 css)
    最近更新 更多