Search code examples
phpalgorithmrenderpixel

Pixel Drawing Algorithm


I need an example algorithm that will draw pixels one at a time on a grid based (x,y) system, and also color them based on an rbg value based on binary data that is provided in some form. I am looking for anything written in php or a php like language such as C, but that does not use any sort of library or graphics card api, as i am coding in php.

Here is something that i wrote in php, that uses random color values but it takes 15 seconds to render in an html canvas:

<?php
$r_max = 240;
$c_max = 320;
$row = -1;//-1 to offset while
while ($row<$r_max){
    ++$row;
    for($column=0; $column<=$c_max; ++$column)
    {
    echo 'ctx.fillStyle = "rgb(', rand()%255, ',', rand()%255, ',', rand()%255, ')";';
    echo 'ctx.fillRect(', $column, ',', $row, ',1,1);';
    }
}
?>

Solution

  • It seem you are trying to output JavaScript commands for drawing on a <canvas> tag. A faster way to draw the pixels might be to use moveTo and lineTo. Btw, why isn't you outer loop a for loop as well?

    Doesn't

    for($row=0; $row<=$r_max; ++$row) {
        for($column=0; $column<=$c_max; ++$column) {
            # draw pixel
        }
    }
    

    seem more natural?