Commit df8b7559 authored by O'Reilly Media, Inc's avatar O'Reilly Media, Inc
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

README.md

0 → 100644
+15 −0
Changes for README.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
## Example files for the title:  
  
# Canvas Pocket Reference, by David Flanagan
  
[![Canvas Pocket Reference, by David Flanagan](http://akamaicovers.oreilly.com/images/9781449396800/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781449398941//)
  
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
  
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
  
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
  
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
  
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.

example_code/README

0 → 100644
+35 −0
Changes for example_code/README: 35 added lines, 0 removed lines.
Original line number Diff line number Diff line
These files are the examples from the book Canvas Pocket Reference
(ISBN: 978-1-449-39680-0) by David Flanagan. The examples are copyright
2011 by O'Reilly Media.  You can use them under the terms of O'Reilly's
code reuse policy:

      This book is here to help you get your job done. In general, you
      may use the code in this book in your programs and
      documentation. You do not need to contact us for permission unless
      you're reproducing a significant portion of the code. For example,
      writing a program that uses several chunks of code from this book
      does not require permission.  Selling or distributing a CD-ROM of
      examples from O'Reilly books does require permission. Answering a
      question by citing this book and quoting example code does not
      require permission.  Incorporating a significant amount of example
      code from this book into your product's documentation does require
      permission.

      We appreciate, but do not require, attribution. An attribution
      usually includes the title, author, publisher, and ISBN. For
      example: "From _Canvas Pocket Reference_, by David
      Flanagan. Copyright 2011 O'Reilly Media, Inc., 978-1-449-39680-0".

      If you feel your use of code examples falls outside fair use of
      the permission given above, feel free to contact us at
      permissions@oreilly.com.

The numbered examples in the book are in files whose names begin with
"example".  There are a few places in the book where useful chunks of
code appear without example numbers.  Those chunks are in files whose
name begins with "page".

I hope these examples are helpful to you!

     David Flanagan
+39 −0
Changes for example_code/example1.js: 39 added lines, 0 removed lines.
Original line number Diff line number Diff line
// Define a regular polygon with n sides, centered at (x,y)
// with radius r. The vertices are equally spaced along the
// circumference of a circle. Put the first vertex straight
// up or at the specified angle. Rotate clockwise, unless
// the last argument is true.
function polygon(c,n,x,y,r,angle,counterclockwise) {
    angle = angle || 0;
    counterclockwise = counterclockwise || false;
    // Compute vertex position and begin a subpath there
    c.moveTo(x + r*Math.sin(angle), 
             y - r*Math.cos(angle));
    var delta = 2*Math.PI/n;     // Angle between vertices
    for(var i = 1; i < n; i++) { // For remaining vertices
        // Compute angle of this vertex
        angle += counterclockwise?-delta:delta; 
        // Compute position of vertex and add a line to it
        c.lineTo(x + r*Math.sin(angle),
                 y - r*Math.cos(angle));
    }
    c.closePath(); // Connect last vertex back to the first
}

// Start a new path and add polygon subpaths
c.beginPath();
polygon(c, 3, 75, 100, 50);              // Triangle
polygon(c, 4, 225, 100, 50, Math.PI/4);  // Square
polygon(c, 5, 375, 100, 50);             // Pentagon
polygon(c, 6, 525, 100, 50, Math.PI/6);  // Hexagon
// Add a small counterclockwise square inside the hexagon
polygon(c, 4, 525, 100, 20, Math.PI/4, true); 

// Set properties that control how the graphics will look
c.fillStyle = "#ccc";    // Light-gray interiors
c.strokeStyle = "#008";  // outlined with dark-blue lines
c.lineWidth = 5;         // five pixels wide.

// Now draw all the polygons (each in its own subpath)
c.fill();                // Fill the shapes
c.stroke();              // And stroke their outlines
+21 −0
Changes for example_code/example10.js: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
// Returns true if the specified mouse event is over a
// non-transparent pixel.
function hitpaint(context, event) {
    // Convert mouse event coordinates to canvas coordinates
    var canvas = context.canvas;
    var bb = canvas.getBoundingClientRect();  
    var x=(event.clientX-bb.left)*(canvas.width/bb.width);
    var y=(event.clientY-bb.top)*(canvas.height/bb.height);

    // Get the pixel (or pixels if multiple device pixels
    // map to 1 CSS pixel) at those coordinates
    var pixels = c.getImageData(x,y,1,1);
    
    // If any pixels have a non-zero alpha, return true
    for(var i = 3; i < pixels.data.length; i+=4) {
        if (pixels.data[i] !== 0) return true;
    }
    
    // Otherwise it was a miss.
    return false;
}
+98 −0
Changes for example_code/example11.js: 98 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*
 * Find all elements of CSS class "sparkline", parse their
 * content as a series of numbers, and replace it with a
 * graphical representation.
 *
 * Define sparklines with markup like this:
 *   <span class="sparkline">3 5 7 6 6 9 11 15</span>
 *
 * Style sparklines with CSS like this:
 *   .sparkline { background-color: #ddd; color: red; }
 *
 * - Sparkline color is from the computed style of the CSS
 *   color property.
 * - Sparklines are transparent, so the normal background
 *   color shows through.
 * - Sparkline height is from the data-height attribute if
 *   defined or from the computed style for the font-size
 *   otherwise.
 * - Sparkline width is from the data-width attribute if it
 *   is defined or the number of data points times data-dx
 *   if that is defined or the number of data points times
 *   the height divided by 6
 * - The minimum and maximum values of the y axis are taken
 *   from the data-ymin and data-ymax attributes if they 
 *   are defined, and otherwise come from the minimum and
 *   maximum values of the data.
 */
// Run this code when the document first loads
window.addEventListener("load", function() {
    // Find all elements of class "sparkline"
    var elts = document.getElementsByClassName("sparkline");
    // Loop through those elements
    main: for(var e = 0; e < elts.length; e++) { 
        var elt = elts[e];

        // Get content of the element and convert to an
        // array of numbers.  If the conversion fails, skip
        // this element.
        var content = elt.textContent || elt.innerText;
        // Trim leading and trailing whitespace
        var content = content.replace(/^\s+|\s+$/g, "");
        // Remove comments
        var text = content.replace(/#.*$/gm, "");
        // Convert newlines, etc., to spaces
        text = text.replace(/[\n\r\t\v\f]/g, " ");
        // Split numbers on commas or spaces
        var data = text.split(/\s+|\s*,\s*/);
        // For each split piece of the string
        for(var i = 0; i < data.length; i++) {
            data[i] = Number(data[i]); // Convert to number
            if (isNaN(data[i]))        // On failure
                continue main;         // skip this elt.
        }

        // Now compute the color, width, height, and y axis
        // bounds of the sparkline from the data, from data-
        // attributes of the element, and from the computed
        // style of the element
        var style = getComputedStyle(elt, null); 
        var color = style.color;
        var height =
            parseInt(elt.getAttribute("data-height")) ||
            parseInt(style.fontSize) || 20;
        var datadx = parseInt(elt.getAttribute("data-dx"));
        var width =
            parseInt(elt.getAttribute("data-width")) ||
            data.length*(datadx || height/6);
        var ymin =
            parseInt(elt.getAttribute("data-ymin")) ||
            Math.min.apply(Math, data);
        var ymax =
            parseInt(elt.getAttribute("data-ymax")) ||
            Math.max.apply(Math, data);
        if (ymin >= ymax) ymax = ymin + 1;

        // Create the canvas element
        var canvas = document.createElement("canvas"); 
        canvas.width = width;     // Set canvas dimensions
        canvas.height = height;
        // Use the element content as a tooltip
        canvas.title = content;   
        elt.innerHTML = "";      // Erase existing content
        elt.appendChild(canvas); // Insert canvas into elt

        // Now plot the points in the canvas
        var context = canvas.getContext('2d');
        for(var i = 0; i < data.length; i++) { 
            // Transform (i,data[i]) to canvas coordinates
            var x = width*i/data.length;
            var y = (ymax-data[i])*height/(ymax-ymin);
            // Draw a line to (x,y). Note that the first
            // call to lineTo() does a moveTo() instead.
            context.lineTo(x,y); 
        }
        context.strokeStyle = color; // Specify color
        context.stroke();            // and draw it
    }
}, false);  // last argument to addEventListener()
Loading