gpt4 book ai didi

javascript - 在 HTML5 Canvas 中绘制任意形状

转载 作者:行者123 更新时间:2023-11-28 03:33:21 30 4
gpt4 key购买 nike

我正在尝试使用 HTML5 canvas 元素绘制图形。该图由顶点和连接这些顶点的边组成。我用小圆圈表示顶点,用连​​接圆圈的线表示边。

在我的项目中,我想在按下“下一步”按钮时更改顶点的位置。下面显示的是页面首次加载时 Canvas 的状态:

enter image description here

单击“下一步”按钮时,将根据顶点的新坐标重新绘制图形。但是,渲染似乎有错误,如下所示:

enter image description here

奇怪的是,我没有在任何地方使用 fill() 函数,所以我无法理解为什么要填充部分。以下是用于绘制图形的 draw() 函数的代码:

function draw(position)
{
var canvas_elem = document.getElementById('drawing');

// Check the element is in the DOM and the browser supports canvas
if(canvas_elem.getContext)
{
// Initaliase a 2-dimensional drawing context
var canvas = canvas_elem.getContext('2d');

// Clear canvas
canvas.clearRect(0, 0, canvas_elem.width, canvas_elem.height);

var data = data_array[num_vertices+1+position].split(",");

// Draw all vertices
for( var i=0; i<num_vertices; i++)
{
canvas.arc(data[2*i], data[2*i+1], radius, 0, 2 * Math.PI, false);
canvas.fillStyle = 'black';
canvas.fill();
}

// Connect vertices by lines according to adjacency matrix
for(var i=0;i<num_vertices; i++)
{
for(var j=i; j<num_vertices; j++)
{
if(adjacency[i][j]==1)
{
canvas.beginPath();
canvas.moveTo(data[2*i],data[2*i+1]);
canvas.lineTo(data[2*j],data[2*j+1]);
canvas.stroke();
}
}
}
}
else
{
alert("Please use an HTML5 compatible browser.");
}
}

关于这里可能发生的事情的任何线索?


取以下这些变量的值进行调试:

data_array=[
"10",
"0,1,1,0,0,0,0,0,0,0",
"1,0,0,1,0,0,0,0,0,1",
"1,0,0,0,1,0,0,0,0,1",
"0,1,0,0,0,1,0,0,1,1",
"0,0,1,0,0,0,1,0,1,1",
"0,0,0,1,0,0,0,1,1,0",
"0,0,0,0,1,0,0,1,1,0",
"0,0,0,0,0,1,1,0,0,0",
"0,0,0,1,1,1,1,0,0,0",
"0,1,1,1,1,0,0,0,0,0",
"10,2,35.4,23.3,88.9,100,210,350,70,500,412,208,336,112,45,32,89,92,102,23",
"30,4,19.4,35.3,80.9,90,230,310,120,440,400,220,330,105,40,29,80,89,90,18"
]

num_vertices=10

最佳答案

好吧,一个愚蠢的错误。我忘记在绘制每条线后调用 closePath()。

关于javascript - 在 HTML5 Canvas 中绘制任意形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199207/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com