Last active
February 6, 2017 11:51
-
-
Save ToxicTree/d56b39a7f2fbb15d28534d9d15230322 to your computer and use it in GitHub Desktop.
HTML5 Canvas: Pixel manipulation with X & Y
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var c = document.getElementById("myCanvas"); | |
var ctx = c.getContext("2d"); | |
// Create some imgData (100 x 100) | |
var imgData = ctx.createImageData(100, 100); | |
// Fill every pixel red in imgData | |
// Example from: http://www.w3schools.com/tags/canvas_imagedata_data.asp | |
var i; | |
for (i = 0; i < imgData.data.length; i += 4) { | |
imgData.data[i+0] = 255; | |
imgData.data[i+1] = 0; | |
imgData.data[i+2] = 0; | |
imgData.data[i+3] = 255; | |
} | |
// Fill every pixel and use X & Y coordinates | |
var w = 100; // Width | |
var h = 100; // Height | |
for (x = 0 ; x < w ; x++) { | |
for (y = 0 ; y < h ; y++) { | |
// Every pixel is 4 in length (RGBA) | |
// Each row is 4 * Width in imgData | |
imgData.data[(x*4)+(y*w*4)+0] = y*2; // RED | |
imgData.data[(x*4)+(y*w*4)+1] = 255; // GREEN | |
imgData.data[(x*4)+(y*w*4)+2] = 0; // BLUE | |
imgData.data[(x*4)+(y*w*4)+3] = 255; // APLHA | |
} | |
} | |
// If scaling canvas (make it larger with CSS), | |
// This will make pixels sharp | |
ctx.imageSmoothingEnabled = false; | |
// Put imgData on canvas at position 10,10 | |
ctx.putImageData(imgData, 10, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment