在这种特定情况下,如何在 HTML5 画布上重绘圆?(方法调用与直接使用上下文对象)

how can I redraw a circle on an HTML5 canvas in this specific case? (method call versus directly using context object)

本文关键字:调用 方法 对象 上下文 情况下 HTML5      更新时间:2023-09-26

我正在尝试创建一个完全包含在HTML画布中的网站。画布应始终调整大小以适合浏览器窗口,并且其中包含的元素应相应地调整大小。

我正在<脚本>(function() {} )(); 编写我所有的 JS,以便它在页面加载后运行。

我在函数的开头全局声明我的画布和上下文,如下所示:

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");

然后我有一个 Circle 对象,它有以下方法:

this.drawCircularBackground = function()
{
    context.beginPath()
    //row and col are passed to the constructor, and indicate the position of the circle
    //on a grid within the canvas, making the position relative to canvas dimensions
    context.arc(canvas.width/16*this.col, canvas.height/16*this.row, 30, 0, 2*Math.PI, false)
    context.fillStyle = "black"
    context.fill();
}   

我有一个网络对象,其中包含一个这样的圆圈数组。

然后我有一个 Page 对象,它包含网络对象的实例,并有一个 resizeCanvas 方法:

this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
//only drawing one circle for now, to test
this.network.circles[0].drawCircularBackground();

此方法与通过此行调整窗口大小相关联,在 initialize() 函数中,该函数在所有这些代码的底部调用以启动网站。

function initialize()
{
   var page = new Page()
    window.addEventListener('resize', page.resizeCanvas, false);
    page.resizeCanvas()
}

到目前为止,此代码在画布的左上角绘制一个半径为 30 的圆。 但是,当我调整窗口大小时,圆圈消失了。如果我替换此行...

this.network.circles[0].drawCircularBackground();

该行调用的函数中的代码...

//this.network.circles[0].drawCircularBackground();
context.beginPath()
//row and col are passed to the constructor, and indicate the position of the circle
//on a grid within the canvas, making the position relative to canvas dimensions
context.arc(canvas.width/16*this.col, canvas.height/16*this.row, 30, 0, 2*Math.PI, false)
context.fillStyle = "black"
context.fill();

当我调整窗口大小时,圆圈仍然可见,并更改相对于画布大小的位置*

所以我被难住了。为什么在调整窗口大小时,用于绘制圆的不同上下文会产生不同的结果?是否可以在与窗口调整大小事件关联的函数中间接调用绘图?

它似乎有效...我刚刚将画布和上下文变量更改为全局变量,因为我不知道您在哪里或如何存储它们。也许这就是你的问题所在。

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var Circle = function (col, row) {
  this.col = col;
  this.row = row;
};
Circle.prototype.drawCircularBackground = function () {
  context.beginPath();
  context.arc(
    canvas.width/16*this.col, 
    canvas.height/16*this.row, 
    30, 0, 2*Math.PI, false
  );
  context.fillStyle = "black";
  context.fill();
};
var network = {
  circles: [new Circle(1,1)]
};
var Page = function () {};
Page.prototype.resizeCanvas = function () {
  context.clearRect(0, 0, canvas.width, canvas.height);
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  network.circles[0].drawCircularBackground();  
};
var initialize = function () {
   var page = new Page();
   window.addEventListener('resize', page.resizeCanvas, false);
   page.resizeCanvas();
};
initialize();
<canvas id="canvas"></canvas>

游乐场:http://jsbin.com/dinabasapi/1/edit?js,output