Last active
December 19, 2015 17:58
-
-
Save webpigeon/5994941 to your computer and use it in GitHub Desktop.
Creating a HTML 5 Canvas
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>HTML5 Canvas example</title> | |
<meta charset="UTF-8"> | |
<script type="text/javascript"> | |
//run this when the window loads | |
window.onload = function() { | |
//function we're going to attach the file upload event to | |
function onFileUpload(evt) { | |
//get the file the user wants to upload | |
var userFile = evt.target.files[0]; | |
//check that the file is an image file | |
if (!userFile.type.match("image/*")) { | |
alert("That is not an image"); | |
return; | |
} | |
//create a file reader and override it's onload event. | |
var reader = FileReader(); | |
reader.onload = function(f) { | |
//create a new image and override it's onload event. | |
var image = new Image(); | |
image.onload = function() { | |
//set the canvas to the width and height of the image | |
var canvas = document.getElementById("drawing"); | |
canvas.width = image.width; | |
canvas.height = image.height; | |
//draw the image though the context | |
var context = canvas.getContext("2d"); | |
context.drawImage(image, 0, 0); | |
} | |
//set the image source to be the data | |
image.src = f.target.result; | |
} | |
//use the reader to read the file | |
reader.readAsDataURL(userFile); | |
} | |
function onButtonPush() { | |
//get the canvas and context from the page | |
var canvas = document.getElementById("drawing"); | |
var context = canvas.getContext("2d"); | |
//get all the canvas data | |
var cData = context.getImageData(0, 0, canvas.width, canvas.height); | |
//Iterate though the array, pixel by pixel | |
//only every 4th item because of (R,G,B,A) | |
for (var i=0; i<cData.data.length; i += 4) { | |
var r = cData.data[i]; | |
var g = cData.data[i+1]; | |
var b = cData.data[i+2]; | |
//var a = cData.data[i+3]; We don't care about this one... | |
//invert the rgb values | |
cData.data[i] = 255 - r; | |
cData.data[i+1] = 255 - g; | |
cData.data[i+2] = 255 - b; | |
} | |
//save the changed data back to the canvas | |
context.putImageData(cData, 0, 0); | |
} | |
//attach events to the document elements | |
document.getElementById('upload').addEventListener('change', onFileUpload, false); | |
document.getElementById('invertbtn').addEventListener('click', onButtonPush, false); | |
} | |
</script> | |
</head> | |
<body> | |
<form> | |
<canvas id="drawing"></canvas><br /> | |
<input type="file" id="upload" /><br /> | |
<input type="button" id="invertbtn" value="invert image" /> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment