Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to draw on an HTML5 Canvas, pixel-by-pixel
    primarykey
    data
    text
    <p>Suppose that I have a 900x900 HTML5 Canvas element.</p> <p>I have a function called <code>computeRow</code> that accepts, as a parameter, the number of a row on the grid and returns an array of 900 numbers. Each number represents a number between 0 and 200. There is an array called <code>colors</code> that contains an array of strings like <code>rgb(0,20,20)</code>, for example.</p> <p>Basically, what I'm saying is that I have a function that tells pixel-by-pixel, what color each pixel in a given row on the canvas is supposed to be. Running this function many times, I can compute a color for every pixel on the canvas.</p> <p>The process of running <code>computeRow</code> 900 times takes about 0.5 seconds.</p> <p>However, the drawing of the image takes much longer than that.</p> <p>What I've done is I've written a function called <code>drawRow</code> that takes an array of 900 numbers as the input and draws them on the canvas. <code>drawRow</code> takes lots longer to run than <code>computeRow</code>! How can I fix this?</p> <p><code>drawRow</code> is dead simple. It looks like this:</p> <pre><code>function drawRow(rowNumber, result /* array */) { var plot, context, columnNumber, color; plot = document.getElementById('plot'); context = plot.getContext('2d'); // Iterate over the results for each column in the row, coloring a single pixel on // the canvas the correct color for each one. for(columnNumber = 0; columnNumber &lt; width; columnNumber++) { color = colors[result[columnNumber]]; context.fillStyle = color; context.fillRect(columnNumber, rowNumber, 1, 1); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload