23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

• By copying pixel data from a video, it’s possible with the canvas to dynamically manipulate a<br />

video (without affecting the source, of course). This is a useful technique, even if it’s<br />

processor-intensive; for this latter reason, though, it might not work well on low-power devices.<br />

Here’s an example of frame-by-frame video manipulation, the technique for which is nicely outlined<br />

in a Windows team blog post, Canvas Direct Pixel Manipulation. 53 In the VideoEdit example for this<br />

chapter, default.html contains a video and canvas element in its main body:<br />

<br />

<br />

In code (js/default.js), we call startVideo from within the activated handler. This function starts the<br />

video and uses requestAnimationFrame to do the pixel manipulation for every video frame:<br />

var video1, canvas1, ctx;<br />

var colorOffset = { red: 0, green: 1, blue: 2, alpha: 3 };<br />

function startVideo() {<br />

video1 = document.getElementById("video1");<br />

canvas1 = document.getElementById("canvas1");<br />

ctx = canvas1.getContext("2d");<br />

}<br />

video1.play();<br />

requestAnimationFrame(renderVideo);<br />

function renderVideo() {<br />

//Copy a frame from the video to the canvas<br />

ctx.drawImage(video1, 0, 0, canvas1.width, canvas1.height);<br />

//Retrieve that frame as pixel data<br />

var imgData = ctx.getImageData(0, 0, canvas1.width, canvas1.height);<br />

var pixels = imgData.data;<br />

//Loop through the pixels, manipulate as needed<br />

var r, g, b;<br />

for (var i = 0; i < pixels.length; i += 4) {<br />

r = pixels[i + colorOffset.red];<br />

g = pixels[i + colorOffset.green];<br />

b = pixels[i + colorOffset.blue];<br />

}<br />

//This creates a negative image<br />

pixels[i + colorOffset.red] = 255 - r;<br />

pixels[i + colorOffset.green] = 255 - g;<br />

pixels[i + colorOffset.blue] = 255 - b;<br />

//Copy the manipulated pixels to the canvas<br />

ctx.putImageData(imgData, 0, 0);<br />

53 See also http://beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation/.<br />

415

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!