繁体   English   中英

无法在画布上画线

[英]Can't draw a line on the canvas

我在用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行没有变黑的解释/修复。

您没有设置画布尺寸。

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

您需要设置实际的画布大小,例如:

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

请记住,当您设置height / width ,会清除画布(即使该值与当前大小相同),也要记住,要获得像素完美的图形,您需要将画布的大小保持为与元素相同的大小。页面(即cnvs.offsetWidthcnvs.offsetHeight )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM