A few years back I WROTE A TUTORIAL CALLED "THE SECRET BEHIND THE PAGE FLIP TECHNIQUE" for Silverlight Developers while working as Creative Director at the experience agency, cynergy. that blog post isn't available anymore, and I haven't touched Silverlight in a while, but even now, I still get several requests for the solution.
As I 've been on-ramping my skills with HTML5, I decided to kill two birds with one stone and solve from scratch the advanced Page Flip Technique with Canvas. while underlying math is very similar, drawing, rotation and clipping are very different between Canvas in HTML5 and Silverlight, so I had to work out quite a few new tricks, highlighted below.
HANDLING TOUCH AND CONSTRAINTS
Source: study1.js
The page flip above and all the interactive math limits strations work with the mouse, but also work with touch events from an iPhone or iPad and with the msPointer events for Internet Explorer 10 and the Windows 8 Consumer Preview. in order to get this to work, I found some great articles online, most notably Handling Multi-Touch and mouse input in all browsers from the IEBlog. I pulled out what I needed for the platforms I was targeting and wrapped the main functions in a file called PointerFusion. js, which you will find in the code behind. you call PointerFusion. js by passing in a DIV that will house your Canvas element, along with the down, move and up functions you want linked to it like so:
var targets;
if (document.querySelectorAll)
{
targets = document.querySelectorAll(".DivStudy1");
if ( targets.length > 0 ) {
PointerFusion(targets[0], onMouseDown, onMouseMove, onMouseUp);
} else {
return;
}
}
If you look at study1.js, you'll see that the init () function kicks everything off, and after sending the DIV target to PointerFusion to enable mouse/pointer/touch interactions, sets up the Canvas elements and wires up a resize listener to call SetSizes () so the DIV and Canvas elements can support a responsive layout (like this blog) and will continue to work on a smaller iPhone/Windows Phone 7 screen up to an iPad/Microsoft Tablet or full Windows 8/IE10 browser.
The "math" part of the page flip is very straightforward for this first step, and is all handled in the function renderMath (). mainly, we setup a point that represents the mouse (or touch, or pointer, etc .) shown above[M]And a generic follow point[F]That provides some graceful easing. Our red node represents the corner of the page[C]And will always try and align itself[F]. However, since we are mapping a physical page flip, the corner of the page[C]Needs to have two constraints. You can't turn the page 'upward 'more than the page width allows without tearing the page, so from Spine Bottom[SB]To the Edge Bottom[EB], We create the first radius constraint[R1]. A physical page being turned also can't be turned 'downward 'more than the page diagonal without ripping, so by taking the diagonal from the Spine Top[ST]To [EB], we create the second radius constraint[R2].
So as we finish step1.js, we have a Canvas that dynamically resizes itself to it's DIV container for a responsive layout, a DIV that is wired for mouse, touch and pointers and renders acceptably in iPhone, iPad, Windows Phone 7, touch optimized Windows 8 experiences, and the common mouse. dragging your finger moves the corner[C], But only within the constraints defined[R1]And[R2]. Not a bad start, there is still a lot more.
CALCULATING THE CRITICAL TRIANGLE
Source: study2.js
In order for the page flip technique to work, we need to calculate a critical triangle that gives us the angle of the page being flipped, as well as the angle of the clipping mask. this triangle is formed by finding the bisector[T0]Of the corner[C]And the edge bottom[EB]. Once we have[T0], We shoot out a line perpendicular to the bisector toward the page bottom[T1]. You then close up the triangle[T2].
Here is what the math looks like:
bisector.x = corner.x + .5*(edgeBottom.x - corner.x);
bisector.y = corner.y + .5*(edgeBottom.y - corner.y);
bisectorAngle = Math.atan2(edgeBottom.y - bisector.y, edgeBottom.x - bisector.x);
bisectorTangent = bisector.x - Math.tan(bisectorAngle) * (edgeBottom.y - bisector.y);
if ( bisectorTangent < 0 ) bisectorTangent = 0;
tangentBottom.x = bisectorTangent;
tangentBottom.y = edgeBottom.y;
bisectorBottom.x = bisector.x;
bisectorBottom.y = tangentBottom.y;
THE PAGE AND THE CLIPPING REGION
Source: study3.js
Once we have the critical triangle, we have the angles required to calculate the position and rotation of both the page sheet and what will become our Clipping Region. if you look at the code for study3.js, you'll see that the work is done in a function called drawsheets (). the two angles we care about are the pageangle and the clipangle. they are calculated like so:
var clipAngle = Math.atan2(tangentBottom.y - bisector.y, tangentBottom.x - bisector.x);
if ( clipAngle < 0 ) clipAngle += Math.PI;
clipAngle -= Math.PI/2;
Placing and rotating the page canvas (shown in red) is relatively straight forward. The place it[C]And rotate it by the calculatedPageAngle. The code looks like this:
clipctx.save();
clipctx.translate(corner.x, corner.y);
clipctx.rotate(pageAngle);
clipctx.drawImage(sheetctx.canvas,0,-pageHeight);
clipctx.restore();
Calculating the Clipping Region is a bit harder. We need to make sure the Clipping Region is fixed[T1], But rotatedClipAngle. To do this, I wrote a helper function that takes in a point and an angle of rotation and returns that value rotated around und [T1]. The function looks like this:
function rotateClipPoint(_p, angle) {
var result = new Point();
_p.x -= tangentBottom.x;
_p.y -= tangentBottom.y;
result.x = (_p.x * Math.cos(angle)) - (_p.y*Math.sin(angle));
result.y = Math.sin(angle)*_p.x + Math.cos(angle)*_p.y;
result.x += tangentBottom.x;
result.y += tangentBottom.y;
return result;
}
Once we have those clipping points, for Study3 we use them define a filled path that represents the clipping region we will use later (shown in blue ). in the final step, we will use these calculated points to define an actual clipping path for a canvas that wraps the page canvas being rendered.
IMPLEMENTING THE CLIP
Source: study4.js
The biggest challenge in implementing the Page Flip technique in Canvas isn' t the math, but figuring out the clipping. the problem I ran into was that drawing content from a canvas into another canvas first in retained mode and then applying a clip function wouldn't work. however, if I defined the clip first and then attempted to save () restore () on the drawing context to draw a rotated element, re Store () call wocould also wipe out the clip! If you don't understand what that means, just play with it enough and trust me, you will. It was infuriating.
The way I was able to work around it was two fold. I needed to force a full drawing context reset by setting the width property on the parent canvas and rotate, nest, render and clip from scratch on every loop. there are three canvas and drawing context we are using in Study 4. sheetCTX is the canvas drawing context we are using for our page placeholder (if you look at the final code for PageFlip. js you will see that SheetCTX is not only responsible for the page being flipped, but also the dynamic shadow of the page curl as well ). sheetCTX is rendered into the drawing context of the wrapper canvas that handles the clipping, called ClipCTX. once the position and angle of the page is rendered into SheetCTX, ClipCTX uses the clipping points to define a Clipping path region and render SheetCTX into itself. at this point, we render SheetCTX into our main drawing context, CTX to interact with the rest of the elements on the screen. the full function looks like so:
function drawSheets()
{
var pageAngle = Math.atan2(tangentBottom.y - corner.y, tangentBottom.x - corner.x);
var clipAngle = Math.atan2(tangentBottom.y - bisector.y, tangentBottom.x - bisector.x);
if ( clipAngle < 0 ) clipAngle += Math.PI;
clipAngle -= Math.PI/2;
sheetCanvas.width = pageWidth;
sheetctx.fillStyle = "rgba(255,0,0,.3)";
sheetctx.fillRect(0,0,pageWidth, pageHeight);
// CALCULATE THE CLIPPING CORNERS
clipPoint0 = rotateClipPoint(new Point(tangentBottom.x, tangentBottom.y+50), clipAngle);
clipPoint1 = rotateClipPoint(new Point(tangentBottom.x-pageWidth, tangentBottom.y+50), clipAngle);
clipPoint2 = rotateClipPoint(new Point(tangentBottom.x-pageWidth, tangentBottom.y-550), clipAngle);
clipPoint3 = rotateClipPoint(new Point(tangentBottom.x, tangentBottom.y-550), clipAngle);
// RESET THE CLIPCANVAS AND CREATE CLIPPING REGION
clipCanvas.width = WIDTH;
clipctx.beginPath();
clipctx.moveTo(clipPoint0.x, clipPoint0.y);
clipctx.lineTo(clipPoint1.x, clipPoint1.y);
clipctx.lineTo(clipPoint2.x, clipPoint2.y);
clipctx.lineTo(clipPoint3.x, clipPoint3.y);
clipctx.closePath();
clipctx.clip();
// DRAW THE UPDATED PAGE BEING TURNED
clipctx.translate(corner.x, corner.y);
clipctx.rotate(pageAngle);
clipctx.drawImage(sheetctx.canvas,0,-pageHeight);
// DRAW THE CORNER
ctx.drawImage(clipctx.canvas,0,0);
}
CONCLUSION
The final PageFlip experience shown at the top of this post is built directly on top of Study4, but uses graphics for the Pages being flipped and some well placed (and calculated) shadow PNGs to help encrypt the Sion. creating a professional level Page Flip experience in Canvas was a great learning experience for myself and hopefully the code and techniques abve will help you ramp up your own skills. for sure there are optimizations that can be done and the technique shown only handles flipping "from the bottom", but the solution shocould be scalable to fit your needs.
There is a lot of potential with HTML5 and Canvas, even in the face of a more "responsive layout" web and multiple interaction metaphors into SS different devices. if you create something awesome with any of this, please put a link in the comments. I 'd love to check it out!
Reprinted: http://rbarraza.com/html5-canvas-pageflip/
Http://world.yo2.cn/articles/page-turn-flip-algorithm.html