我无法使用 JavaScript 在 HTML 画布上画线。作为记录,我不想使用任何预先编写的画线方法,我需要使用像素操作来完成。我尝试在 500x500 像素的画布上画一条线,我已经用它提供了数据
function drawBackgtoundAndLine()
{
var cnvs = document.getElementById("cnvs");
var cont = cnvs.getContext("2d")
var imdt = cont.getImageData(0,0,500,500)
//Fill canvas with a color
for ( var i = 0 ; i < imdt.data.length ; i = i + 4)
{
imdt.data[i] = 200;
imdt.data[i+1] = 100;
imdt.data[i+2] = 0;
imdt.data[i+3] = 255;
}
//Draw a horizontal line
var index = 0;
for ( var c = 0 ; c < 500 ; c++)
{
index = (4*c)+488000;
imdt.data[index] = 0;
imdt.data[index+1] = 0;
imdt.data[index+2] = 0;
imdt.data[index+3] = 255;
}
cont.putImageData( imdt , 0 , 0 )
}
你可以在这个小提琴中看到它的作用。顺便说一句,我的数学让我第二个 for 循环画一条线是:我想为整个第 245 行着色。因此,要通过前 244 行,我将 2000(每行中的数据点数)乘以 244 行得到 488000。然后我循环循环 500 次以命中行中的每个像素,并添加 488000到达正确的行。我真的很感谢第 245 行没有变黑的解释/修复。