【问题标题】:canvas arc too pixelated画布弧度太像素化
【发布时间】:2020-05-19 01:51:43
【问题描述】:

我尝试在画布上画一个圆圈,我以前做过,但这次我发现它非常像素化

var game;

function game (){

    this.canvas = document.getElementById('canvas');

    this.ctx = this.canvas.getContext('2d');



    this.initCanvas = function(){

    }

    this.draw1 = function(){
        this.ctx.beginPath();
        this.ctx.arc(50, 75, 10, 0, Math.PI*2, true); 
        this.ctx.closePath();
        this.ctx.fill();
    }

    this.draw2 = function(){
        this.ctx.beginPath();
        this.ctx.arc(100,75,10,0,Math.PI*2,true);
        this.ctx.closePath();
        this.ctx.stroke();
    }

    this.run = function(){
        this.initCanvas();
        this.draw1();
        this.draw2();
    }

    window.onresize = function() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
    };
}

game = new game();

http://jsfiddle.net/RG6dn/6/

我不知道这是由于浏览器(我在 chrome 和 firefox 上有同样的东西)还是我的电脑

谢谢

【问题讨论】:

    标签: html canvas geometry


    【解决方案1】:

    您可能正在使用 CSS 设置画布的宽度。在 CSS 中更改画布元素的宽度会拉伸画布内的像素

    例如。

    <canvas style='width:400px;height:400px'></canvas>

    相反,您需要使用画布元素本身的宽度和高度属性来定义画布包含多少像素。

    正确方法:

    <canvas width='400px' height='400px'><canvas>

    【讨论】:

    • 这对我有帮助。你知道为什么会这样吗?
    • 因为画布是按像素绘制的,所以需要定义画布本身的像素数。 CSS 仅指示宽度/高度(以像素为单位),而不是实际在画布内的像素数
    • 最好添加 haw 以使用 javaScript 以编程方式执行此操作(例如在页面调整大小时对其进行修改)
    【解决方案2】:

    这篇文章不是最近的,但它帮助我解决了我的问题,但答案中有错误。 当我们初始化画布的高度和宽度时,我们不会传递一个以“px”为单位的字符串,而只是一个带有数字的字符串。像这样:

    <canvas width='400' height='400'><canvas>
    

    Ajouve : 在你的代码中你犯了一个错误,在纠正错误后它可以工作

     var game;
    
     function game (){
    
     this.initCanvas = function(){
         this.canvas = document.getElementById('canvas');
         this.ctx = this.canvas.getContext('2d');   
     }
    
     this.draw1 = function(){
         this.ctx.beginPath();
         this.ctx.arc(50, 75, 10, 0, Math.PI*2, true); 
         this.ctx.closePath();
         this.ctx.fill();
     }
    
     this.draw2 = function(){
         this.ctx.beginPath();
         this.ctx.arc(100,75,10,0,Math.PI*2,true);
         this.ctx.closePath();
         this.ctx.stroke();
     }
        // Here define your fonction for resizing canvas
         this.resize = function() {
         this.canvas.width = window.innerWidth;
         this.canvas.height = window.innerHeight;
     };
    
     this.run = function(){
         this.initCanvas();
         // Call your function here
         this.resize();
         this.draw1();
         this.draw2();
     }
    
    }
    
       game = new game();
    
       game.run();
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多