javascript - 无法在 Canvas 上画线

标签 javascript html canvas pixel-manipulation

我无法使用 JavaScript 在 HTML Canvas 上绘制线条。根据记录,我不想使用任何预先编写的线条绘制方法,我需要使用像素操作来完成。我尝试在 500x500 像素 Canvas 上画一条线,我已经用此提供了数据

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 )
}

您可以在 this 中看到它的实际效果。 fiddle 。顺便说一句,我的数学计算给了我第二个 for 循环来画一条线: 我想为整个第 245 行着色。因此,为了传递前 244 行,我将 2000(每行中的数据点数量)乘以 244 行得到 488000。然后我循环执行该循环 500 次以命中该行中的每个像素,并将 488000 相加到达正确的行。我真的很感谢对第 245 行不变黑的解释/修复。

最佳答案

您没有设置 Canvas 大小。

请注意,CSS 大小仅与显示有关,与 Canvas 中的像素数量无关。

您需要设置实际 Canvas 大小,例如:

 cnvs.width = 500;
 cnvs.height = 500;

请记住,当您设置高度/宽度时, Canvas 会被清除(即使该值与当前大小相同),还要记住要获取像素- 完美的图形,您需要保持 Canvas 大小与页面上的元素大小相同(即cnvs.offsetWidthcnvs.offsetHeight)。

关于javascript - 无法在 Canvas 上画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599627/

相关文章:

javascript - knockout javascript foreach 绑定(bind)

javascript - 将 id 添加到对象数组

javascript - Bootstrap 减小字体大小

canvas - Three.js:如何在缩放时保持 Sprite 文字大小不变

javascript - 从 Highstock 中的 RangeSelector 获取当前选中的范围

javascript - 加载时,带有资源 View 的 Fullcalendar 无法在 ASP.NET MVC 中工作 - 0x800a01bd - javaScript 运行时错误 : Object doesn't support this action

javascript - 移动 Web 应用程序 - 多页面还是 AJAX?

javascript - 使用javascript将具有多个图像的html div转换为单个图像

canvas - Flutter:开始使用 Canvas

canvas - SwiftUI 预览 SKProduct 和介绍性价格