html5画布上下文在整页中模糊

时间:2019-02-01 09:49:23

标签: html5 canvas

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

绿色背景上的红色矩形:

the red rectangle, on green background

当我使画布的宽度和高度==窗口的宽度和高度(整页)时。即使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();
    });

});

1 个答案:

答案 0 :(得分:0)

您的代码正在画布上调用<script> alert("Quote Emailed Successfully."); history.back(); </script> .width()方法。这不会更改画布的.height()height属性,而是会更改其widthheight的样式,从而使它看起来很拉伸。而是使用width更改画布的.attr()height属性。

请参见下面的工作示例:

width
$(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;
}