Nigel  Uys

Nigel Uys

1669357380

How to Use The DrawImage() Method To Draw an Image

JavaScript canvas drawImage() method explained

The drawImage() method is a method from the Canvas API that allows you to add an image into your <canvas> element.

Just like the fillRect() method, the drawImage() method is a part of Canvas 2D API, so you need to get the Context object of your <canvas> element first and call the method from there.

For example, suppose you have the following <canvas> and <img> element in your HTML page:

<body>
  <canvas
    id="myCanvas"
    width="300"
    height="300"
    style="background-color: red"
  ></canvas>
  <img
    id="imgSource"
    src="image.jpg"
    style="display:none;"
  />
</body>

The style="background-color: red" is added to the <canvas> element so you can see the edge of the canvas. Also, notice how the <img> element is hidden from view using the style="display:none;" attribute.

Let’s put the image inside the canvas. First, get the 2D context of the Canvas with the getContext() method as follows:

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");

The drawImage() method requires three parameters to work:

  • The image object element
  • The x coordinate to place the object in the canvas
  • The y coordinate to place the object in the canvas

Here’s an example of adding the image with the id of imgSource to the canvas:

let img = document.getElementById("imgSource");
ctx.drawImage(img, 50, 50);

The code above will add the image element to the canvas. Here’s an example of my canvas using a JavaScript logo image with the size of 200 X 200:

drawImage() method in actiondrawImage() method in action

While the drawImage() method requires only three parameters to work, you can actually pass a total of 9 parameters to the method, depending on what you want to do with the object.

To place an image to the canvas, you need to pass three parameters as you’ve seen previously: The image element, the x coordinate, and the y coordinate to draw the image.

drawImage(image, x, y);

Next, you can also adjust the width and height of the image by passing two optional parameters (five parameters in total)

drawImage(image, x, y, width, height);

Finally, you can also clip the image and add the clipped image to your canvas by passing four additional parameters:

  • The sx and sy coordinate to start clipping the image
  • The sWidth and sHeight parameters to determine the width and height of the clip
ctx.drawImage(img, sx, sy, sWidth, sHeight, x, y, width, height);

For example, here’s the snippet to clip the JavaScript logo, where only the JS letter is visible from the image:

ctx.drawImage(img, 50, 80, 140, 120, 50, 50, 140, 120);

The result would be as follows:

drawImage() method clipping the JS logodrawImage() method clipping the JS logo

You might wonder why you still need to pass the width and height of the image (the last two parameters) to add to the canvas when you’re using the clipped image.

This is because you can still resize the image after clipping. Without specifying the width and height of the image, the drawImage() method will throw the Overload resolution failed error.

And that’s how you can use the drawImage() method to add one or more images to a <canvas> element. When you draw multiple images to the canvas, don’t forget to specify a different x and y parameters for each image, or your next image will stack on top of the previous image.

Original article source at: https://sebhastian.com/

#javascript #canvas #method 

How to Use The DrawImage() Method To Draw an Image
Sheldon  Grant

Sheldon Grant

1669278904

How to Save JavaScript Canvas Image As Data URL using ToDataURL()

Saving canvas image as Data URL using toDataURL() method

The toDataURL() method is a method from the Canvas API that allows you to store an image drawn on top of the <canvas> element in the form of a Data URL scheme.

The Data URL scheme allows you to embed an image in-line inside your HTML, saving you one extra HTTP request that would otherwise be performed for that image.

The method accepts two optional parameters:

  • The type string for the image format. Defaults to image/png
  • The imageQuality number for image types that use lossy compression like image/jpeg. The value must be between 0 and 1 with the default value being 0.92

Let’s see the method in action. Suppose you’ve created a <canvas> element as follows:

<body>
  <canvas
    id="emptyCanvas"
    width="300"
    height="300"
  ></canvas>
  <script>
    let canvas = document.getElementById("emptyCanvas");
    let ctx = canvas.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.fillRect(50, 100, 150, 150);
  </script>
</body>

The code above will produce a rectangle drawing in your web browser as follows:

An image created using HTML CanvasAn image created using HTML Canvas

To transform the image drawn into a Data URL, you only need to call the toDataURI() method on the canvas object:

const dataURL = canvas.toDataURL();
console.log(dataURL);

The console.log() result would be as follows. The ellipsis ... in the second line omits the rest of the output and the third line shows the end of the URI:

data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAALBElEQ...
ooAghcEBCsC6puIoDACQHBOsHqKAIIXBAQrAuqbiKAwAmBP7PLLTzDQluOAAAAAElFTkSuQmCC

The format of the scheme is as shown below:

data:[<mime type>][;charset=<charset>][;base64],<encoded data>

The encoded data is a very long string that the browser will render as an image. You need to pass the entire scheme as the src attribute of an <img> element.

To test the data scheme, you can copy and pass the Data URL into a new browser window to see the image rendered using the <img> element. Notice how the data:image/png scheme entered into the address bar below:

Image Data URL rendered on the browserImage Data URL rendered on the browser

By transforming the image to a Data URL scheme, you can embed any image rendered inside the <canvas> element in any web page without making an extra HTTP request.

But keep in mind that the Data URL scheme is not recommended for large images or images that are changed frequently because the scheme is not cached by the browser, meaning that the image will be downloaded each time the page is loaded.

On the other hand, an HTTP request for the image can be cached by the browser so that the image will be served from the cache when the page is loaded again.

Original article source at: https://sebhastian.com/

#javascript #image #canvas 

How to Save JavaScript Canvas Image As Data URL using ToDataURL()
Nat  Grady

Nat Grady

1665530520

Create interactive Creatures in RMarkdown Documents and Shiny Apps

creature

The goal of the package is to create a creature that will accompany you when you feel lonely. You will find it at the bottom of your Rmd document or Shiny app. The creature was initially developed by Justin Windle, I’ve just found it cool and adapted it to R. You can say this is an R wrapper.

creature.gif

Installation

You can install the development version from GitHub with:


# install.packages("remotes")

remotes::install_github("feddelegrand7/creature")

Example

A demo is available here

Code of Conduct

Please note that the creature project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Download Details:

Author: Feddelegrand7
Source Code: https://github.com/feddelegrand7/creature 
License: Unknown, MIT licenses found

#r #javascript #canvas #shiny 

Create interactive Creatures in RMarkdown Documents and Shiny Apps
Nat  Grady

Nat Grady

1665526380

Fabricerin: Create Easily Canvas in Shiny and RMarkdown Documents

fabricerin

The fabricerin (spelled fabrikerine) package allows you to create easily canvas elements within your Shiny app and RMarkdown documents. Thanks to Garrick Aden-Buie, you can also use it within your xaringan slides. You can use the canvas to render shapes, images and text. You can also create a canvas for drawing/taking notes purposes. Under the hoods, fabricerin relies on the fabricjs JavaScript library.

Installation

You can install fabricerin from CRAN with:

install.packages("fabricerin")

You can install the development version from GitHub with:

# install.packages("remotes")

remotes::install_github("feddelegrand7/fabricerin")

Examples:

First of all, I’d like to state that all the example provided apply the same way to Shiny and Rmd documents. fabricerin is not an R wrapper for the fabricjs library. The package doesn’t cover all the capabilities of the library. The fabricerin package relies only on some specified features that according to me will help Shiny/Rmd users. Of course, if you need some improvement, feel free to create a Pull Request.

fabric_drawing() Create a canvas for taking notes


fabric_drawing() is pretty useful when you want to teach something and write some notes at the same time, below I provide an example using the xaringan package. Inside a xaringan slide you can just (for example) run R code in the left and take notes in the right:

Important: When you change a color, make sure that the erase box is not checked.

t_example.gif

fabric_drawing() can be used the same way in Shiny:

library(shiny)
library(fabricerin)


ui <- fluidPage(
  
  
  fabric_drawing(cid = "canvas123")

)

server <- function(input, output){}

shinyApp(ui, server)

example1.gif

fabric_shape() Render shape objects in canvas


Currently, fabricerin supports three types of shapes: Rectangle, Triangle, Circle and Polygon. The user can interact with the shape and modify its position, size and rotation. If you want to disable this interactivity, you can set selectable =FALSE

library(shiny)
library(fabricerin)


ui <- fluidPage(
  

  fabric_shape(cid = "canvaId", # canvas id
               cfill = "orange", # canvas color
               cwidth = 800, # the width of the canvas
               cheight = 600, # the height of the canvas
               shapeId = "shapeId", # shape id
               shape = "Rect", 
               fill = "red", # shape color
               width = 400, 
               height = 400, 
               left = 100, # the position of the shape from the left relative to the canvas
               top = 100, # the position of the shape from the top relative to the canvas
               strokecolor = "darkblue", 
               strokewidth = 5, 
               selectable = TRUE)
  
)

server <- function(input, output){}

shinyApp(ui, server)

example3.gif

You can add as many shape as you want to an existing canvas using the fabric_shape_add() function. Don’t forget to reference the preexisting canvas with its ID:

library(shiny)
library(fabricerin)


ui <- fluidPage(
  
  
  fabric_shape(cid = "canvaId", 
               shapeId = "cr1", 
               shape = "Circle", 
               radius = 30, 
               left = 100), 
  
  fabric_shape_add(cid = "canvaId", 
                   shapeId = "cr2", 
                   shape = "Circle", 
                   radius = 30, 
                   left = 200),
  
  fabric_shape_add(cid = "canvaId", 
                   shapeId = "cr3", 
                   shape = "Circle", 
                   radius = 30, 
                   left = 300),
  
  fabric_shape_add(cid = "canvaId", 
                   shapeId = "cr4", 
                   shape = "Circle", 
                   radius = 30, 
                   left = 400)
  
)

server <- function(input, output){}

shinyApp(ui, server)

fabric_image() Render images in canvas


You can insert an image within a canvas a play with it using the fabric_image() function. Note that this function accepts only URL external images.

ui <- fluidPage(

fabric_image(cid = "cimage",
              cfill = "lightblue",
              imgId = "Rimg",
              imgsrc = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/R_logo.svg/724px-R_logo.svg.png")

              )

server <- function(input, output) {}


shinyApp(ui = ui, server = server)

example5.gif

Similar to shapes, you can add images to preexisting canvas using the fabric_image_add() function:

library(shiny)
library(fabricerin)

ui <- fluidPage(

 fabric_image(cid = "cimage",
              imgId = "Rimg",
              imgsrc = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/R_logo.svg/724px-R_logo.svg.png",
              imgheight = 200,
              imgwidth = 200),
 fabric_image_add(cid = "cimage",
                  imgId = "rstudioimg",
                  imgsrc = "https://raw.githubusercontent.com/rstudio/hex-stickers/master/PNG/dplyr.png",
                  imgwidth = 200,
                  imgheight = 200,
                  left = 400)
                  )

server <- function(input, output) {}

shinyApp(ui = ui, server = server)

fabric_text() Render text elements in canvas


The fabric_text() function has many arguments, feel free to check them out:

ui <- fluidPage(

fabric_text(cid = "cId",
          textId = "text",
          text = " 'But A Hero Is A Guy Who Gives Out The Meat To Everyone Else. \\n I Want To Eat The Damn Meat!' \\n Monkey D. Luffy",
          cfill = "#DD5347",
          left = 120,
          shadowCol = "blue",
          fontSize = 20,
          fontWeight = "bold",
          lineHeight = 3
          )
)
server <- function(input, output) {}

shinyApp(ui = ui, server = server)

example6.gif

Here also, we can use the fabric_text_add() function to incorporate a text object within a canvas element:

library(shiny)
library(fabricerin)


ui <- fluidPage(

fabric_shape(cid = "canvas123",
              cfill = "lightblue",
              cwidth = 1000,
              shapeId = "tri1",
              shape = "Triangle",
              fill = "darkblue"),

fabric_text_add(cid = "canvas123",
                 textId = "txt1",
                 text = "This is a darkblue Triangle !",
                 left = 350
                 )

                 )

server <- function(input, output) {}

shinyApp(ui = ui, server = server)

fabric_curtail() Add a background or an overlay image to a canvas

You can set an image as a background or as a foreground (overlay) for a canvas as follows:

Note that due to security reasons, you won’t be able to replicate the following example on some images’ sources.

ui <- fluidPage(

 fabric_shape(cid = "canvas123",
              shapeId = "tri1",
              shape = "Triangle",
              fill = "lightblue"),

fabric_curtail(cid = "canvas123",
              imgsrc = "https://st.depositphotos.com/1642482/1904/i/950/depositphotos_19049237-stock-photo-leaf.jpg",
              type = "background"

              )

)

server <- function(input, output) {}


shinyApp(ui = ui, server = server)

Code of Conduct

Please note that the fabricerin project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Download Details:

Author: feddelegrand7
Source Code: https://github.com/feddelegrand7/fabricerin 
License: Unknown, AGPL-3.0 licenses found

#r #javascript #canvas #shiny 

Fabricerin: Create Easily Canvas in Shiny and RMarkdown Documents
Nat  Grady

Nat Grady

1665381547

CanvasXpress: A JavaScript Library for Data analytics with Full Audit

canvasXpress was developed as the core visualization component for bioinformatics and systems biology analysis at Bristol-Myers Squibb. It supports a large number of visualizations to display scientific and non-scientific data. canvasXpress also includes a simple and unobtrusive user interface to explore complex data sets, a sophisticated and unique mechanism to keep track of all user customization for Reproducible Research purposes, as well as an 'out of the box' broadcasting capability to synchronize selected data points in all canvasXpress plots in a page. Data can be easily sorted, grouped, transposed, transformed or clustered dynamically. The fully customizable mouse events as well as the zooming, panning and drag-and-drop capabilities are features that make this library unique in its class.

canvasXpress can be now simply used within R at the console to generate conventional plots, in R-Studio or seamlessly embedded in Shiny web applications. Full-fledged examples of the canvasXpress library including the mouse events, zooming, and broadcasting capabilities are included in this package in several examples that can be accessed using the cxShinyExample function. This canvasXpress R library was created with the htmlwidgets package.

Installation

canvasXpress is available for installation from CRAN or you can install the latest version of canvasXpress from GitHub as follows:

devtools::install_github('neuhausi/canvasXpress')

Examples

These are included to get you started on basic charting - there are many more examples (including complex and compound visualizations) with R code available in the Examples section of the main website at https://www.canvasxpress.org

Scatter 3D Plot

y <- read.table("https://www.canvasxpress.org/data/cX-irist-dat.txt", header=TRUE, sep="\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
z <- read.table("https://www.canvasxpress.org/data/cX-irist-var.txt", header=TRUE, sep= "\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)

canvasXpress(data      = y,
             varAnnot  = z,
             graphType ="Scatter3D",
             colorBy   = "Species",
             ellipseBy = "Species",
             xAxis     = list("Sepal.Length"),
             yAxis     = list("Petal.Width"),
             zAxis     = list("Petal.Length"),
             theme     = "CanvasXpress",
             title     = "Iris Data Set",
             axisTickScaleFontFactor  = 0.5,
             axisTitleScaleFontFactor = 0.5)

Scatter3D

Scatter 2D Matrix Plot

y <- read.table("https://www.canvasxpress.org/data/cX-irist-dat.txt", header=TRUE, sep="\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
z <- read.table("https://www.canvasxpress.org/data/cX-irist-var.txt", header=TRUE, sep= "\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)

canvasXpress(data              = y,
             varAnnot          = z,
             graphType         = "Scatter2D",
             colorBy           = "Species",
             layoutAdjust      = TRUE,
             scatterPlotMatrix = TRUE,
             theme             = "CanvasXpress")

Scatter2DMatrix

Boxplot

y <- read.table("https://www.canvasxpress.org/data/cX-toothgrowth-dat.txt", header=TRUE, sep="\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
x <- read.table("https://www.canvasxpress.org/data/cX-toothgrowth-smp.txt", header=TRUE, sep="\t", 
                quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)

canvasXpress(data                  = y,
             smpAnnot              = x,
             graphType             = "Boxplot",
             groupingFactors       = list("dose", "supp"),
             stringSampleFactors   = list("dose"),
             graphOrientation      = "vertical",
             colorBy               = "dose",
             title                 = "The Effect of Vitamin C on Tooth Growth in Guinea Pigs",
             smpTitle              = "dose",
             xAxisTitle            = "len",
             smpLabelRotate        = 90,
             xAxisMinorTicks       = FALSE,
             xAxis2Show            = FALSE,
             legendScaleFontFactor = 1.8)

Boxplot

Heatmap (Multi-dimensional)

y  <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-dat.txt", header=TRUE, sep="\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
y2 <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-dat2.txt", header=TRUE, sep="\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
y3 <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-dat3.txt", header=TRUE, sep="\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
y4 <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-dat4.txt", header=TRUE, sep="\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
x  <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-smp.txt", header=TRUE, sep= "\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
z  <- read.table("https://www.canvasxpress.org/data/cX-multidimensionalheatmap-var.txt", header=TRUE, sep= "\t", 
                 quote="", row.names=1, fill=TRUE, check.names=FALSE, stringsAsFactors=FALSE)

canvasXpress(data                 = list(y = y, data2 = y2, data3 = y3, data4 = y4),
             smpAnnot             = x,
             varAnnot             = z,
             graphType            = "Heatmap",
             guides               = TRUE,
             outlineBy            = "Outline",
             outlineByData        = "data2",
             shapeBy              = "Shape",
             shapeByData          = "data3",
             sizeBy               = "Size",
             sizeByData           = "data4",
             showHeatmapIndicator = FALSE,
             afterRender          = list(list("clusterSamples")))

Heatmap

Four way Venn Diagram

canvasXpress(vennData   = data.frame(AC=456, A=340, ABC=552, ABCD=148, BC=915, ACD=298, BCD=613, 
                                     B=562, CD=143, ABD=578, C=620, D=592, AB=639, BD=354, AD=257),
             graphType  = "Venn",
             vennLegend = list(A="List 1", D="List 4", C="List 3", B="List 2"),
             vennGroups = 4)

Venn

More Examples and Resources

In addition to the built-in package documentation there are vignettes with more information on getting started and additional examples:

#List all package vignettes
vignette(package = "canvasXpress")

#View a specific vignette
vignette("getting_started", package = "canvasXpress")
vignette("additional_examples", package = "canvasXpress")

For the use of canvasXpress plots in shiny there are interactive examples available through the package function cxShinyExample

#List example names
cxShinyExample()

#Run an interactive shiny example
cxShinyExample(example = "example1")

There is also a wealth of additional information including full API documentation and extensive R and JavaScript examples at https://www.canvasxpress.org.

Download Details:

Author: Neuhausi
Source Code: https://github.com/neuhausi/canvasXpress/ 

#r #canvas #visualization #javascript

CanvasXpress: A JavaScript Library for Data analytics with Full Audit

A Package with Classes to Help Testing Applications using The Canvas

Canvas test helpers

[MockCanvas] is a utility class for writing tests for canvas operations. It supports the same API as the regular [Canvas] class from dart:ui (in theory; any missing commands can be added as the need arises). In addition, this class is also a [Matcher], allowing it to be used in expect() calls as can be seen in the example below.

Two mock canvases will match only if they have the same number of commands, and if each pair of corresponding commands matches.

Multiple transform commands (translate(), scale(), rotate() and transform()) that are issued in a row are always joined into a single combined transform. Thus, for example, calling translate(10, 10) and then translate(30, -10) will match a single call translate(40, 0).

Some commands can be partially specified. For example, in drawLine() and drawRect() the paint argument is optional. If provided, it will be checked against the actual Paint used, but if omitted, the match will still succeed.

Commands that involve numeric components (i.e. coordinates, dimensions, etc) will be matched approximately, with the default absolute tolerance of 1e-10.

Example Usage

final canvas = MockCanvas();
// ... draw something on the canvas
// then check that the commands issued were the ones that you'd expect:
expect(
  canvas,
  MockCanvas()
    ..translate(10, 10)
    ..drawRect(const Rect.fromLTWH(0, 0, 100, 100)),
);

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add canvas_test_helpers

With Flutter:

 $ flutter pub add canvas_test_helpers

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  canvas_test_helpers: ^0.1.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:canvas_test_helpers/canvas_test_helpers.dart'; 

Download Details:

Author: 

Source Code: https://pub.dev/packages/canvas_test_helpers

#canvas #flutter #android 

A Package with Classes to Help Testing Applications using The Canvas
Reid  Rohan

Reid Rohan

1664923200

Pure JS Implementation Of The HTML Canvas 2D Drawing API

PureImage

PureImage is a pure 100% JavaScript implementation of the HTML Canvas 2D drawing API for NodeJS. It has no native dependencies. You can use it to resize images, draw text, render badges, convert to grayscale, or anything else you could do with the standard Canvas 2D API.

Installation

npm install pureimage

Simple example

Make a 100x100 image, fill with red, write to png file

import * as PImage from "pureimage"
import * as fs from 'fs'

// make image
const img1 = PImage.make(100, 100)

// get canvas context
const ctx = img1.getContext('2d');

// fill with red
ctx.fillStyle = 'red';
ctx.fillRect(0,0,100,100);

//write to 'out.png'
PImage.encodePNGToStream(img1, fs.createWriteStream('out.png')).then(() => {
    console.log("wrote out the png file to out.png");
}).catch((e)=>{
    console.log("there was an error writing");
});

result

red square

supported Canvas Features

note: PureImage values portability and simplicity of implementation over speed. If you need maximum performance you should use a different library backed by native code, such as Node-Canvas

  • set pixels
  • stroke and fill paths (rectangles, lines, quadratic curves, bezier curves, arcs/circles)
  • copy and scale images (nearest neighbor)
  • import and export JPG and PNG from streams using promises
  • render basic text (no bold or italics yet)
  • anti-aliased strokes and fills
  • transforms
  • standard globalAlpha and rgba() alpha compositing
  • clip shapes

On the roadmap, but still missing

  • gradients fills
  • image fills
  • blend modes besides SRC OVER
  • smooth clip shapes
  • bold/italic fonts
  • smooth image interpolation

Why?

The are more than enough drawing APIs out there. Why do we need another? My personal hatred of C/C++ compilers is widely known. The popular Node modules Canvas.js does a great job, but it's backed by Cairo, a C/C++ layer. I hate having native dependencies in Node modules. They often don't compile, or break after a system update. They often don't support non-X86 architectures (like the Raspberry Pi). You have to have a compiler already installed to use them, along with any other native dependencies pre-installed (like Cairo).

So, I made PureImage. It's goal is to implement the HTML Canvas spec in a headless Node buffer. No browser or window required.

PureImage is meant to be a small and maintainable Canvas library. It is not meant to be fast. If there are two choices of algorithm we will take the one with the simplest implementation, and preferably the fewest lines. We avoid special cases and optimizations to keep the code simple and maintainable. It should run everywhere and be always produce the same output. But it will not be fast. If you need speed go use something else.

PureImage uses only pure JS dependencies. OpenType for font parsing, PngJS for PNG import/export, and jpeg-js for JPG import/export.

Examples

Make a new empty image, 100px by 50px. Automatically filled with 100% opaque black.

var PImage = require('pureimage');
var img1 = PImage.make(100,50);

Fill with a red rectangle with 50% opacity

var ctx = img1.getContext('2d');
ctx.fillStyle = 'rgba(255,0,0, 0.5)';
ctx.fillRect(0,0,100,100);

Fill a green circle with a radius of 40 pixels in the middle of a 100px square black image.

var img = PImage.make(100,100);
var ctx = img.getContext('2d');
ctx.fillStyle = '#00ff00';
ctx.beginPath();
ctx.arc(50,50,40,0,Math.PI*2,true); // Outer circle
ctx.closePath();
ctx.fill();

image of arcto with some fringing bugs

Draw the string 'ABC' in white in the font 'Source Sans Pro', loaded from disk, at a size of 48 points.

test('font test', (t) => {
    var fnt = PImage.registerFont('test/fonts/SourceSansPro-Regular.ttf','Source Sans Pro');
    fnt.load(() => {
        var img = PImage.make(200,200);
        var ctx = img.getContext('2d');
        ctx.fillStyle = '#ffffff';
        ctx.font = "48pt 'Source Sans Pro'";
        ctx.fillText("ABC", 80, 80);
    });
});

Write out to a PNG file

PImage.encodePNGToStream(img1, fs.createWriteStream('out.png')).then(() => {
    console.log("wrote out the png file to out.png");
}).catch((e)=>{
    console.log("there was an error writing");
});

Read a jpeg, resize it, then save it out

PImage.decodeJPEGFromStream(fs.createReadStream("test/images/bird.jpg")).then((img) => {
    console.log("size is",img.width,img.height);
    var img2 = PImage.make(50,50);
    var c = img2.getContext('2d');
    c.drawImage(img,
        0, 0, img.width, img.height, // source dimensions
        0, 0, 50, 50                 // destination dimensions
    );
    var pth = path.join(BUILD_DIR,"resized_bird.jpg");
    PImage.encodeJPEGToStream(img2,fs.createWriteStream(pth), 50).then(() => {
        console.log("done writing");
    });
});

This examples streams an image from a URL to a memory buffer, draws the current date in big black letters, and writes the final image to disk

import * as PImage from "pureimage"
import fs from 'fs'
import * as client from "https"

let url = "https://vr.josh.earth/webxr-experiments/physics/jinglesmash.thumbnail.png"
let filepath = "output.png"
//register font
const font = PImage.registerFont('test/unit/fixtures/fonts/SourceSansPro-Regular.ttf','MyFont');
//load font
font.load(() => {
    //get image
    client.get(url, (image_stream)=>{
        //decode image
        PImage.decodePNGFromStream(image_stream).then(img => {
            //get context
            const ctx = img.getContext('2d');
            ctx.fillStyle = '#000000';
            ctx.font = "60pt MyFont";
            ctx.fillText(new Date().toDateString(), 50, 80);
            PImage.encodePNGToStream(img, fs.createWriteStream(filepath)).then(()=>{
                console.log("done writing to ",filepath)
            })
        });
    })
})

produces

stream example

The same as above but with Promises

import * as PImage from "pureimage"
import fs from 'fs'
import * as client from "https"

let url = "https://vr.josh.earth/webxr-experiments/physics/jinglesmash.thumbnail.png"
let filepath = "output.png"
let fontpath = 'test/unit/fixtures/fonts/SourceSansPro-Regular.ttf'
PImage.registerFont(fontpath,'MyFont').loadPromise()
    //Promise hack because https module doesn't support promises natively)
    .then(()=>new Promise(res => client.get(url,res)))
    .then(stream => PImage.decodePNGFromStream(stream))
    .then(img => {
        //get context
        const ctx = img.getContext('2d');
        ctx.fillStyle = '#000000';
        ctx.font = "60pt MyFont";
        ctx.fillText(new Date().toDateString(), 50, 80);
        return PImage.encodePNGToStream(img, fs.createWriteStream(filepath))
    })
    .then(()=>{
        console.log('done writing',filepath)
    })

New 0.3.x release

After a long lull, I've ported the code to modern ES6 modules, so you can just do an import pureimage from 'pureimage' like any other proper modern module. If you are using require('pureimage') it should just work thanks to the dist/pureimage-umd.cjs file built with Rollup. It also has a stub to let pureimage run in the browser and delegate to the real HTML canvas. This helps with isomorphic apps.

Other updates include

  • Switch to MochaJS for the unit tests.
  • add more unit tests.
  • support drawing images when using transforms
  • implement rect()
  • implement ImageData with getImageData() and putImageData()
  • fix gradient fill
  • add all CSS named colors
  • support #rgb, #rgba, and #rrggbbaa color strings
  • applied more bug fixes from PRs, thanks to our contributors.

New 0.1.x release

I've completely refactored the code so that it should be easier to maintain and implement new features. For the most part there are no API changes (since the API is defined by the HTML Canvas spec), but if you were using the font or image loading extensions you will need to use the new function names and switch to promises. For more information, please see the API docs

I'm also using Node buffers instead of arrays internally, so you can work with large images faster than before. Rich text is no longer supported, which is fine because it never really worked anyway. We'll have to find a different way to do it.

I've tried to maintain all of the patches that have been sent in, but if you contributed a patch please check that it still works. Thank you all! - josh

Thanks!

Thanks to Nodebox / EMRG for opentype.js

Thanks to Rosetta Code for Bresenham's in JS

Thanks to Kuba Niegowski for PngJS

Thanks to Eugene Ware for jpeg-js

Thanks for patches from:

Download Details:

Author: joshmarinacci
Source Code: https://github.com/joshmarinacci/node-pureimage 
License: MIT license

#javascript #html #node #drawing  #canvas 

Pure JS Implementation Of The HTML Canvas 2D Drawing API
Lawrence  Lesch

Lawrence Lesch

1664456280

Signature_pad: HTML5 Canvas Based Smooth Signature Drawing

Signature Pad

Signature Pad is a JavaScript library for drawing smooth signatures. It's HTML5 canvas based and uses variable width Bézier curve interpolation based on Smoother Signatures post by Square. It works in all modern desktop and mobile browsers and doesn't depend on any external libraries.

Installation

You can install the latest release using npm:

npm install --save signature_pad

or Yarn:

yarn add signature_pad

You can also add it directly to your page using <script> tag:

<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script>

You can select a different version at https://www.jsdelivr.com/package/npm/signature_pad.

This library is provided as UMD (Universal Module Definition) and ES6 module.

Usage

API

const canvas = document.querySelector("canvas");

const signaturePad = new SignaturePad(canvas);

// Returns signature image as data URL (see https://mdn.io/todataurl for the list of possible parameters)
signaturePad.toDataURL(); // save image as PNG
signaturePad.toDataURL("image/jpeg"); // save image as JPEG
signaturePad.toDataURL("image/jpeg", 0.5); // save image as JPEG with 0.5 image quality
signaturePad.toDataURL("image/svg+xml"); // save image as SVG

// Draws signature image from data URL (mostly uses https://mdn.io/drawImage under-the-hood)
// NOTE: This method does not populate internal data structure that represents drawn signature. Thus, after using #fromDataURL, #toData won't work properly.
signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...");

// Draws signature image from data URL and alters it with the given options
signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...", { ratio: 1, width: 400, height: 200, xOffset: 100, yOffset: 50 });

// Returns signature image as an array of point groups
const data = signaturePad.toData();

// Draws signature image from an array of point groups
signaturePad.fromData(data);

// Draws signature image from an array of point groups, without clearing your existing image (clear defaults to true if not provided)
signaturePad.fromData(data, { clear: false });

// Clears the canvas
signaturePad.clear();

// Returns true if canvas is empty, otherwise returns false
signaturePad.isEmpty();

// Unbinds all event handlers
signaturePad.off();

// Rebinds all event handlers
signaturePad.on();

Options

dotSize

(float or function) Radius of a single dot.

minWidth

(float) Minimum width of a line. Defaults to 0.5.

maxWidth

(float) Maximum width of a line. Defaults to 2.5.

throttle

(integer) Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.

minDistance

(integer) Add the next point only if the previous one is farther than x pixels. Defaults to 5.

backgroundColor

(string) Color used to clear the background. Can be any color format accepted by context.fillStyle. Defaults to "rgba(0,0,0,0)" (transparent black). Use a non-transparent color e.g. "rgb(255,255,255)" (opaque white) if you'd like to save signatures as JPEG images.

penColor

(string) Color used to draw the lines. Can be any color format accepted by context.fillStyle. Defaults to "black".

velocityFilterWeight

(float) Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.

You can set options during initialization:

const signaturePad = new SignaturePad(canvas, {
    minWidth: 5,
    maxWidth: 10,
    penColor: "rgb(66, 133, 244)"
});

or during runtime:

const signaturePad = new SignaturePad(canvas);
signaturePad.minWidth = 5;
signaturePad.maxWidth = 10;
signaturePad.penColor = "rgb(66, 133, 244)";

Events

beginStroke

Triggered before stroke begins.

endStroke

Triggered after stroke ends.

beforeUpdateStroke

Triggered before stroke update.

afterUpdateStroke

Triggered after stroke update.

You can add listeners to events with .addEventListener:

const signaturePad = new SignaturePad(canvas);
signaturePad.addEventListener("beginStroke", () => {
  console.log("Signature started");
}, { once: true });

Tips and tricks

Handling high DPI screens

To correctly handle canvas on low and high DPI screens one has to take devicePixelRatio into account and scale the canvas accordingly. This scaling is also necessary to properly display signatures loaded via SignaturePad#fromDataURL. Here's an example how it can be done:

function resizeCanvas() {
    const ratio =  Math.max(window.devicePixelRatio || 1, 1);
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
    signaturePad.clear(); // otherwise isEmpty() might return incorrect value
}

window.addEventListener("resize", resizeCanvas);
resizeCanvas();

Instead of resize event you can listen to screen orientation change, if you're using this library only on mobile devices. You can also throttle the resize event - you can find some examples on this MDN page.

When you modify width or height of a canvas, it will be automatically cleared by the browser. SignaturePad doesn't know about it by itself, so you can call signaturePad.fromData(signaturePad.toData()) to reset the drawing, or signaturePad.clear() to make sure that signaturePad.isEmpty() returns correct value in this case.

This clearing of the canvas by the browser can be annoying, especially on mobile devices e.g. when screen orientation is changed. There are a few workarounds though, e.g. you can lock screen orientation, or read an image from the canvas before resizing it and write the image back after.

Handling data URI encoded images on the server side

If you are not familiar with data URI scheme, you can read more about it on Wikipedia.

There are 2 ways you can handle data URI encoded images.

You could simply store it in your database as a string and display it in HTML like this:

<img src="data:image/png;base64,iVBORw0K..." />

but this way has many disadvantages - it's not easy to get image dimensions, you can't manipulate it e.g. to create a thumbnail and it also has some performance issues on mobile devices.

Thus, more common way is to decode it and store as a file. Here's an example in Ruby:

require "base64"

data_uri = "data:image/png;base64,iVBORw0K..."
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }

Here's an example in PHP:

$data_uri = "data:image/png;base64,iVBORw0K...";
$encoded_image = explode(",", $data_uri)[1];
$decoded_image = base64_decode($encoded_image);
file_put_contents("signature.png", $decoded_image);

Here's an example in C# for ASP.NET:

var dataUri = "data:image/png;base64,iVBORw0K...";
var encodedImage = dataUri.Split(',')[1];
var decodedImage = Convert.FromBase64String(encodedImage);
System.IO.File.WriteAllBytes("signature.png", decodedImage);

Removing empty space around a signature

If you'd like to remove (trim) empty space around a signature, you can do it on the server side or the client side. On the server side you can use e.g. ImageMagic and its trim option: convert -trim input.jpg output.jpg. If you don't have access to the server, or just want to trim the image before submitting it to the server, you can do it on the client side as well. There are a few examples how to do it, e.g. here or here and there's also a tiny library trim-canvas that provides this functionality.

Drawing over an image

Demo: https://jsfiddle.net/szimek/d6a78gwq/

Demo

Demo works in desktop and mobile browsers. You can check out its source code for some tips on how to handle window resize and high DPI screens. You can also find more about the latter in HTML5 Rocks tutorial.

Other demos

Download Details:

Author: Szimek
Source Code: https://github.com/szimek/signature_pad 
License: MIT license

#javascript #drawing #canvas #html5 

Signature_pad: HTML5 Canvas Based Smooth Signature Drawing
Lawrence  Lesch

Lawrence Lesch

1664415360

CCapture.js: A Library to Capture Canvas-based animations

CCapture.js - A library to capture canvas-based animations

CCapture.js is a library to help capturing animations created with HTML5 canvas at a fixed framerate.

An example is probably worth a lot of words: CCapture.js with Game of Life 3D.

Sample

What is CCapture.js and why would I need it?

Let's say that you finally have your amazing canvas-based animation running in your browser, be it 2D or 3D with the power of WebGL. You've been working hard to keep it fast and smooth. If you're using requestAnimationFrame you're aiming for a framerate of 60fps or, in other words, each frame is taking 16ms or less to render.

Now you want to record a video of it. Not a big deal, you can fire up a screen capture software that churns out a video file and be done with it. But what if you wanted to create an HD movie of your animation, and it simply cannot be rendered at higher resolutions because frames start dropping? What if you wanted to put all the quality settings up for the video? What if you wanted to push that particle count to 10 millions?

What if, indeed. What would happen is that you'd get a choppy video at best. At higher resolutions, fillrate is a bottleneck for most canvas-based animations. High quality settings or high number of elements may be only feasible on more powerful hardware.

With CCapture.js you can record smooth videos at a fixed framerate for all these situations, because it doesn't run in realtime: it makes the animations run at a given, fixed framerate which can be specified. You can record animations at smooth and consistent 30 or 60fps even if each frame takes seconds to render. You can even take a 240fps capture and create motion blur with post-production software.

The only requirement is that you step your values per frame according to elapsed time. In other words, don't increment your variables with a fixed value each frame, but use an elapsed time delta to adjust those increments. CCapture.js works by hooking the common methods for obtaining that elapsed time: Date.now(), setTimeout, requestAnimationFrame, etc. and making them behave like a constant time step is happening, fixed by the specified framerate.

Methods supported so far:

  • Date.now, Date.prototype.getTime
  • setTimeout, clearTimeout, setInterval (clearInterval pending)
  • requestAnimationFrame
  • performance.now
  • HTMLVideoElement.prototype.currentTime, HTMLAudioElement.prototype.currentTime

CCapture.js is more or less ryg's kkapture but for JavaScript and canvas.

The library supports multiple export formats using modular encoders (`CCFrameEncoder):

  • CCWebMEncoder uses WebM Writer for JavaScript to create a WebM movie
  • CCPNGEncoder and CCJPEGEncoder export PNG and JPEG files in a TAR file, respectively
  • CCGIFEncoder uses gifjs to create animated GIFs
  • CCFFMpegServerEncoder uses ffmpegserver.js to generate video on the server

Forks, pull requests and code critiques are welcome!

Using the code

Include CCapture[.min].js and WebM Writer or gifjs.

<script src="CCapture.min.js"></script>
<!-- Include WebM Writer if you want to export WebM -->
<script src="webm-writer-0.2.0.js"></script>
<!-- Include gifjs if you want to export GIF -->
<script src="gif.js"></script>
<!-- Include tar.js if you want to export PNG or JPEG -->
<script src="tar.js"></script>
<!-- Include download.js for easier file download -->
<script src="download.js"></script>

Or include the whole pack

<script src="CCapture.all.min.js"></script>

Or use npm or bower to install the package:

npm install ccapture.js

Or use bower to install the package:

bower install ccapture.js

To create a CCapture object, write:

// Create a capturer that exports a WebM video
var capturer = new CCapture( { format: 'webm' } );

// Create a capturer that exports an animated GIF
// Notices you have to specify the path to the gif.worker.js 
var capturer = new CCapture( { format: 'gif', workersPath: 'js/' } );

// Create a capturer that exports PNG images in a TAR file
var capturer = new CCapture( { format: 'png' } );

// Create a capturer that exports JPEG images in a TAR file
var capturer = new CCapture( { format: 'jpg' } );

This creates a CCapture object to run at 60fps, non-verbose. You can tweak the object by setting parameters on the constructor:

var capturer = new CCapture( {
    framerate: 60,
    verbose: true
} );

The complete list of parameters is:

  • framerate: target framerate for the capture
  • motionBlurFrames: supersampling of frames to create a motion-blurred frame (0 or 1 make no effect)
  • format: webm/gif/png/jpg/ffmpegserver
  • quality: quality for webm/jpg
  • name: name of the files to be exported. if no name is provided, a GUID will be generated
  • verbose: dumps info on the console
  • display: adds a widget with capturing info (WIP)
  • timeLimit: automatically stops and downloads when reaching that time (seconds). Very convenient for long captures: set it and forget it (remember autoSaveTime!)
  • autoSaveTime: it will automatically download the captured data every n seconds (only available for webm/png/jpg)
  • startTime: skip to that mark (seconds)
  • workersPath: path to the gif worker script

You can decide when to start the capturer. When you call the .start() method, the hooks are set, so from that point on setTimeout, setInterval and other methods that are hooked will behave a bit differently. When you have everything ready to start capturing, and your animation loop is running, call:

capturer.start();

requestAnimationFrame, setTimeout, etc. won't work as expected after capture is started. Make sure your animation loop is running

And then, in your render() method, after the frame is been drawn, call .capture() passing the canvas you want to capture.

function render(){
    requestAnimationFrame(render);
    // rendering stuff ...
    capturer.capture( canvas );
}

render()

That's all. Once you're done with the animation, you can call .stop() and then .save(). That will compose the video and return a URL that can be previewed or downloaded.

capturer.stop();

// default save, will download automatically a file called {name}.extension (webm/gif/tar)
capturer.save();

// custom save, will get a blob in the callback
capturer.save( function( blob ) { /* ... */ } );

Note: you don't need to .stop() in order to .save(). Call capturer.save() anytime you want to get a download up to that moment.

Limitations

CCapture.js only works on browsers that have a `canvas implementation.

WebM Writer current version only works on a browser that supports the image/webp format. Exporting video is basically Chrome-only for now :( If you want to help to make it Firefox, Opera or even Internet Explorer compatible, please do!

gif.js has some performance limitations, be careful if capturing a lot of frames.

The autoSaveTime parameter

Different browsers have different issues with big files: most break for big Uint8Array allocations, or when a file to downloads is larger than 1GB, etc. I haven't been able to find a solid solution for all, so I introduced the autoSaveTime parameter, just to prevent loss of large files. If used with a webm/png/jpg capturer, it will automatically compile, download and free the captured frames every n seconds specified in the parameter. The downloaded file will have the structure {name}-part-00000n and the extension (.webm or .tar). The files inside the TAR file will have the right number of sequence.

Use an autoSaveTime value that give you a file that is small enough to not trip the browser, but large enough to not generate a thousand part files. A value between 10 and 30 seconds for a 4K capture I've found works best: just make sure the file is under 1GB. For most regular, viewport-sized or even Full-HD captures it shouldn't be an issue, but keep in mind this issue.

Memory allocation and garbage collection

There's some issues in which memory -mostly from accumulated frames- will not be freed, depending on the platform and the mood of the browser. If you run into non-sawtooth like memory profiles, and are running chrome, try running it with --js-flags="--expose-gc". This way CCapture will run gc() every frame and memory consumption should stay stable.

Gallery

cru·ci·form 4K CCapture obsidian by xplsv 4K CCapture dataworld by xplsv 4K CCapture

Credits

Contributors

Big thanks to hugohil and Greggman!

Download Details:

Author: Spite
Source Code: https://github.com/spite/ccapture.js/ 
License: MIT license

#javascript  #png #video #canvas 

CCapture.js: A Library to Capture Canvas-based animations
Lawrence  Lesch

Lawrence Lesch

1664407320

Html2canvas: Screenshots with JavaScript

html2canvas

JavaScript HTML renderer

The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

How does it work?

The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements.

It does not require any rendering from the server, as the whole image is created on the client's browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn't magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin.

The script is still in a very experimental state, so I don't recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.

Browser compatibility

The library should work fine on the following browsers (with Promise polyfill):

  • Firefox 3.5+
  • Google Chrome
  • Opera 12+
  • IE9+
  • Safari 6+

As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.

Usage

The html2canvas library utilizes Promises and expects them to be available in the global context. If you wish to support older browsers that do not natively support Promises, please include a polyfill such as es6-promise before including html2canvas.

To render an element with html2canvas, simply call: html2canvas(element[, options]);

The function returns a Promise containing the <canvas> element. Simply add a promise fulfillment handler to the promise using then:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

Building

You can download ready builds here.

Clone git repository:

$ git clone git://github.com/niklasvh/html2canvas.git

Install dependencies:

$ npm install

Build browser bundle

$ npm run build

Examples

For more information and examples, please visit the homepage or try the test console.

Contributing

If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn't supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.

Homepage | Downloads | Questions 

Download Details:

Author: Niklasvh
Source Code: https://github.com/niklasvh/html2canvas 
License: MIT license

#javascript #html #canvas 

Html2canvas: Screenshots with JavaScript
Lawrence  Lesch

Lawrence Lesch

1664395380

Pixijs: The HTML5 Creation Engine

PixiJS - The HTML5 Creation Engine  

The aim of this project is to provide a fast lightweight 2D library that works across all devices. The PixiJS renderer allows everyone to enjoy the power of hardware acceleration without prior knowledge of WebGL. Also, it's fast. Really fast.

If you want to keep up to date with the latest PixiJS news then feel free to follow us on Twitter @PixiJS and we will keep you posted! You can also check back on our site as any breakthroughs will be posted up there too!

What to Use PixiJS for and When to Use It

PixiJS is a rendering library that will allow you to create rich, interactive graphics, cross-platform applications, and games without having to dive into the WebGL API or deal with browser and device compatibility.

PixiJS has full WebGL support and seamlessly falls back to HTML5's canvas if needed. As a framework, PixiJS is a fantastic tool for authoring interactive content, especially with the move away from Adobe Flash in recent years. Use it for your graphics rich, interactive websites, applications, and HTML5 games. Out of the box, cross-platform compatibility and graceful degradation mean you have less work to do and have more fun doing it! If you want to create polished and refined experiences relatively quickly, without delving into dense, low-level code, all while avoiding the headaches of browser inconsistencies, then sprinkle your next project with some PixiJS magic!

Boost your development and feel free to use your imagination!

Learn

  • Website: Find out more about PixiJS on the official website.
  • Getting started:
    • Check out @kittykatattack's comprehensive tutorial.
    • Also check out @miltoncandelero's PixiJS tutorials aimed toward videogames with recipes, best practices and TypeScript / npm / webpack setup here
  • Examples: Get stuck right in and play around with PixiJS code and features right here!
  • Docs: Get to know the PixiJS API by checking out the docs.
  • Guide: Supplementary guide to the API documentation here.
  • Wiki: Other misc tutorials and resources are on the Wiki.

Community

  • Forums: Check out the forum and Stackoverflow, both friendly places to ask your PixiJS questions.
  • Inspiration: Check out the gallery to see some of the amazing things people have created!
  • Chat: You can join us on Discord to chat about PixiJS.

Setup

It's easy to get started with PixiJS! Simply download a prebuilt build!

Alternatively, PixiJS can be installed with npm or simply using a content delivery network (CDN) URL to embed PixiJS directly on your HTML page.

Note: After v4.5.0, support for the Bower package manager has been dropped. Please see the release notes for more information.

NPM Install

npm install pixi.js

There is no default export. The correct way to import PixiJS is:

import * as PIXI from 'pixi.js'

CDN Install (via cdnjs)

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.1.3/pixi.min.js"></script>

Note: 5.1.3 can be replaced by any released version.

Demos

Thanks to @photonstorm for providing those last 2 examples and allowing us to share the source code :)

Contribute

Want to be part of the PixiJS project? Great! All are welcome! We will get there quicker together :) Whether you find a bug, have a great feature request or you fancy owning a task from the road map above feel free to get in touch.

Make sure to read the Contributing Guide before submitting changes.

Current features

  • WebGL renderer (with automatic smart batching allowing for REALLY fast performance)
  • Canvas renderer (Fastest in town!)
  • Full scene graph
  • Super easy to use API (similar to the flash display list API)
  • Support for texture atlases
  • Asset loader / sprite sheet loader
  • Auto-detect which renderer should be used
  • Full Mouse and Multi-touch Interaction
  • Text
  • BitmapFont text
  • Multiline Text
  • Render Texture
  • Primitive Drawing
  • Masking
  • Filters
  • User Plugins

Basic Usage Example

import { Application, Sprite, Assets } from 'pixi.js';

// The application will create a renderer using WebGL, if possible,
// with a fallback to a canvas render. It will also setup the ticker
// and the root stage PIXI.Container
const app = new Application();

// The application will create a canvas element for you that you
// can then insert into the DOM
document.body.appendChild(app.view);

// load the texture we need
const texture = await Assets.load('bunny.png');

// This creates a texture from a 'bunny.png' image
const bunny = new Sprite(texture);

// Setup the position of the bunny
bunny.x = app.renderer.width / 2;
bunny.y = app.renderer.height / 2;

// Rotate around the center
bunny.anchor.x = 0.5;
bunny.anchor.y = 0.5;

// Add the bunny to the scene we are building
app.stage.addChild(bunny);

// Listen for frame updates
app.ticker.add(() => {
    // each frame we spin the bunny around a bit
    bunny.rotation += 0.01;
});

How to build

Note that for most users you don't need to build this project. If all you want is to use PixiJS, then just download one of our prebuilt releases. Really the only time you should need to build PixiJS is if you are developing it.

If you don't already have Node.js and NPM, go install them. Then, in the folder where you have cloned the repository, install the build dependencies using npm:

npm install

Then, to build the source, run:

npm run build

Error installing gl package

In most cases installing gl from npm should just work. However, if you run into problems you might need to adjust your system configuration and make sure all your dependencies are up to date

Please refer to the gl installation guide for more information.

Error installing canvas package

The canvas library currently being used does not have a pre-built version for every environment. When the package detects an unsupported environment, it will try to build from source.

To build from source you will need to make sure you have the following dependencies installed and then reinstall:

brew install pkg-config cairo pango libpng jpeg giflib librsvg

For non-mac users, please refer to the canvas installation guide for more information.

How to generate the documentation

The docs can be generated using npm:

npm run docs

The documentation uses webdoc in combination with this template pixi-webdoc-template. The configuration file can be found at webdoc.conf.json

We are now a part of the Open Collective and with your support you can help us make PixiJS even better. To make a donation, simply click the button below and we'll love you forever!

 

Download Details:

Author: Pixijs
Source Code: https://github.com/pixijs/pixijs 
License: MIT license

#javascript #game #webgl #canvas 

Pixijs: The HTML5 Creation Engine
Nat  Grady

Nat Grady

1664257097

ShinyCanvas: Create & Customize an interactive Canvas Use The 'D3' JS

shinyCanvas

Create and customize an interactive canvas using the 'D3' JavaScript library and the 'htmlwidgets' package.

The canvas can be used directly from the R console, from 'RStudio', in Shiny apps and R Markdown documents.

When in Shiny the canvas is observed by the server and can be used as a functional slider (with animation) to work in a two dimensional space.

The main objective is to create a new object for Shiny that represents a functional slider extending the one dimensional shiny::sliderInput.

For an interactive bl.ock page to try the d3js code go to here.

The user inputs a data.frame that contains corrdinates x,y and then can:

  • add/remove points to the plot
  • change position of the points
  • change the type of interpolation between points
  • run animation on the interpolated curve to collect a sample from it

Usage as an htmlwidget in the RStudio viewer

canvas(obj = data.frame(x=1:10,y=runif(10)))

Usage in a Shiny app

When run in the Shiny environment, Shiny is observing the points and returns to the server their x,y mapping. So instead of predefining scenarios in simulations you can let the user define the relationship between two variables.

Reactive Canvas:

Click Pictures to see Youtube Videos

Basic Usage:

Script to run example below

shinyCanvas in Shiny

Survival Analysis Example:

Bivariate Slider in Shiny

library(shinyCanvas)
library(shiny)
server <- function(input, output) {

  network <- reactiveValues()

  df<-reactive({
    data.frame(Var1=1:10,Var2=sort(rexp(10),decreasing = T))
  })
  
  observeEvent(input$d3_update,{
    netNodes=input$d3_update$.pointsData
    if(!is.null(netNodes)) network$nodes <- jsonlite::fromJSON(netNodes)
    
    pathNodes=input$d3_update$.pathData
    if(!is.null(pathNodes)) network$path <- jsonlite::fromJSON(pathNodes)
  })

  observeEvent(network$nodes,{
    output$pointsOut<-renderTable({
      dat=network$nodes
      colnames(dat)=names(df())
      dat.df=data.frame(Id=1:nrow(dat),dat)
      dat.df
    })    
  })

  observeEvent(network$path,{
    output$pathOut<-renderTable({
      dat=as.data.frame(network$path)
      colnames(dat)=names(df())
      dat=data.frame(Id=1:nrow(dat),dat)
      dat
    })    
  })
  
  output$d3 <- renderCanvas({
    isolate({canvas(obj = df(),animate = TRUE,duration=500,pathRadius=10)})
  })
}

ui <- fluidPage(
  column(6,canvasOutput(outputId="d3")),
  column(3,
         p('Plot Points'),
         tableOutput('pointsOut')
         ),
  column(3,
         p('Path Sample'),
         tableOutput('pathOut')
         )
)

shinyApp(ui = ui, server = server)

Download Details:

Author: Yonicd
Source Code: https://github.com/yonicd/shinyCanvas 
License: View license

#r #d3 #javascript #canvas 

ShinyCanvas: Create & Customize an interactive Canvas Use The 'D3' JS
Mike  Kozey

Mike Kozey

1661420280

Animated Canvas Feature - Use to Mount Animations To Routes

dart_board_canvas

This one is for fun. It provides a way to expose a Route which reveals an indeterminate animated canvas.

This is meant for physics/visual simulations and demo's. If you want access to the canvas to draw something cool, this is it.

It's similar to the flutter "funvas" project, and is designed for quick and dirty graphics work. It does not provide shorthand like funvas does.

Getting Started

Adding to your App

Add DartBoardCanvasFeature to your application, it is configured to be registered multiple times under many namespaces if necessary. It binds an animated widget to a route.

params showFpsOverlay enable an app decoration that will show your canvas/draw performance/fps implementationName & namespace feature registration details route the route this feature will expose stateBuilder Builds the AnimatedCanvasState instance

Implementing canvas effects.

  1. Extend AnimatedCanvasState
  2. implement init(BuildContext context) and dispose() if necessary.
  3. implement paint(Canvas, Size) to draw your thing
  4. EITHER Use DartBoardCanvaFeature to mount your Animation
  5. OR use AnimatedCanvasWidget and give it your state object.

built-in fields/getters accessible in paint() time - The current simulation time timeDelta - The delta time of the frame fps - 1/timeDelta context the active BuildContext this painter is operating in

Funvas Support

https://github.com/creativecreatorormaybenot/funvas

Funvas code can be dropped in as is usually, the shorthand API is supported, and a small amount of code ported. However, we don't bring in funvas directly.

Just drop the funvas code into the paint() method.

I know it's strange to have 2 api's (e.g. time and t), but funvas is really nice, and the programming style of brevity and hacking is nicely in the spirit of this kind of graphics programming. So use the shorthand for fun, use the full names if your writing more readable code.

Ultimately, up to you.

ROADMAP

  • More examples
    • E.g. embedded funvas animations
    • Interactive physics animation

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add dart_board_canvas

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  dart_board_canvas: ^1.3.4

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dart_board_canvas/dart_board_canvas.dart';

Original article source at: https://pub.dev/packages/dart_board_canvas 

#flutter #dart #canvas 

Animated Canvas Feature - Use to Mount Animations To Routes
Rupert  Beatty

Rupert Beatty

1660123380

Canvas: A Laravel Publishing Platform

Introduction

Canvas is a fully open source package to extend your existing Laravel application and get you up-and-running with a blog in just a few minutes. In addition to a distraction-free writing experience, you can view monthly trends on your content, get insights into reader traffic and more!

System Requirements

Installation

You may use composer to install Canvas into your Laravel project:

composer require austintoddj/canvas

Publish the assets and primary configuration file using the canvas:install Artisan command:

php artisan canvas:install

Create a symbolic link to ensure file uploads are publicly accessible from the web using the storage:link Artisan command:

php artisan storage:link

Configuration

After publishing Canvas's assets, a primary configuration file will be located at config/canvas.php. This file allows you to customize various aspects of how your application uses the package.

Canvas exposes its UI at /canvas by default. This can be changed by updating either the path or domain option:

/*
|--------------------------------------------------------------------------
| Base Domain
|--------------------------------------------------------------------------
|
| This is the subdomain where Canvas will be accessible from. If the
| domain is set to null, Canvas will reside under the defined base
| path below. Otherwise, this will be used as the subdomain.
|
*/

'domain' => env('CANVAS_DOMAIN', null),

/*
|--------------------------------------------------------------------------
| Base Path
|--------------------------------------------------------------------------
|
| This is the URI where Canvas will be accessible from. If the path
| is set to null, Canvas will reside under the same path name as
| the application. Otherwise, this is used as the base path.
|
*/

'path' => env('CANVAS_PATH_NAME', 'canvas'),

Sometimes, you may want to apply custom roles or permissions when accessing Canvas. You can create and attach any additional middleware here:

/*
|--------------------------------------------------------------------------
| Route Middleware
|--------------------------------------------------------------------------
|
| These middleware will be attached to every route in Canvas, giving you
| the chance to add your own middleware to this list or change any of
| the existing middleware. Or, you can simply stick with the list.
|
*/

'middleware' => [
    'web',
],

Canvas uses the storage disk for media uploads. You may configure the different filesystem options here:

/*
|--------------------------------------------------------------------------
| Storage
|--------------------------------------------------------------------------
|
| This is the storage disk Canvas will use to put file uploads. You may
| use any of the disks defined in the config/filesystems.php file and
| you may also change the maximum upload size from its 3MB default.
|
*/

'storage_disk' => env('CANVAS_STORAGE_DISK', 'local'),

'storage_path' => env('CANVAS_STORAGE_PATH', 'public/canvas'),

'upload_filesize' => env('CANVAS_UPLOAD_FILESIZE', 3145728),

Roles & Permissions

Canvas comes with 3 pre-defined roles out-of-the-box:

  • Contributor (A user who can write and manage their own posts but cannot publish them)
  • Editor (A user who can publish and manage posts including the posts of other users)
  • Admin (A user who can do everything and see everything)

When you install a fresh version of Canvas, you'll have a default admin user set up automatically. From there, you can perform any basic CRUD actions on users, as well as assign their various roles.

Canvas UI

Want a beautiful, Medium.com-inspired frontend? Use the canvas:ui Artisan command to install the scaffolding:

php artisan canvas:ui

After generating the frontend scaffolding, your package.json file will include the necessary dependencies to install and compile:

# Using NPM
npm install
npm run dev

# Using Yarn
yarn
yarn dev

That's it! You can navigate to /canvas-ui and check it out for yourself. You're free to modify any aspect of it that you'd like.

Unsplash Integration

Want access to the entire Unsplash library? Set up a new application at https://unsplash.com/oauth/applications, grab your access key, and update config/canvas.php:

/*
|--------------------------------------------------------------------------
| Unsplash Integration
|--------------------------------------------------------------------------
|
| Visit https://unsplash.com/oauth/applications to create a new Unsplash
| app. Use the confidential Access Key given to you to integrate with
| the API. Note that demo apps are limited to 50 requests per hour.
|
*/

'unsplash' => [
    'access_key' => env('CANVAS_UNSPLASH_ACCESS_KEY'),
]

E-mail Notifications

Want a weekly summary? Canvas allows users to receive a weekly digest of their authored content. Once your application is configured for sending mail, update config/canvas.php:

/*
|--------------------------------------------------------------------------
| E-Mail Notifications
|--------------------------------------------------------------------------
|
| This option controls e-mail notifications that will be sent via the
| default application mail driver. A default option is provided to
| support the notification system as an opt-in feature.
|
|
*/

'mail' => [
    'enabled' => env('CANVAS_MAIL_ENABLED', false),
]

Since this feature runs on Laravel's Scheduler, you'll need to add the following cron entry to your server:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

API

Installing Canvas UI will be the most efficient way to get up and running with a frontend interface to display your data. However many users will opt for creating this by hand since it gives flexibility to their design aesthetic.

Using the published scope will allow you to only retrieve posts that have a published date in the past:

Canvas\Models\Post::published()->get()

You can also retrieve the inverse with a draft scope:

Canvas\Models\Post::draft()->get()

To return a single post, you'll likely want to find it by a given slug, as well as include related entities such as:

$post = Canvas\Models\Post::with('user', 'tags', 'topic')->firstWhere('slug', $slug);

Important: In the same method that returns a post, make sure you fire the PostViewed event, or else a view/visit will not be recorded.

event(new Canvas\Events\PostViewed($post));

You can find a tag by a given slug:

Canvas\Models\Tag::with('posts')->firstWhere('slug', $slug);

And a similar query can be used for a topic:

Canvas\Models\Topic::with('posts')->firstWhere('slug', $slug);

Users can be retrieved by their id, username, or email:

$user = Canvas\Models\User::find($id);
$user = Canvas\Models\User::firstWhere('username', $username);
$user = Canvas\Models\User::firstWhere('email', $email);

Additionally, you can return the users' published posts with their associated topic:

$user->posts()->published()->with('topic')

Updates

Canvas follows Semantic Versioning and increments versions as MAJOR.MINOR.PATCH numbers.

  • Major versions will contain breaking changes, so follow the upgrade guide for a step-by-step breakdown
  • Minor and patch versions should never contain breaking changes, so you can safely update the package by following the steps below:

You may update your Canvas installation using composer:

composer update

Run any new migrations using the canvas:migrate Artisan command:

php artisan canvas:migrate

Re-publish the assets using the canvas:publish Artisan command:

php artisan canvas:publish

To keep the assets up-to-date and avoid issues in future updates, you may add the canvas:publish command to the post-update-cmd scripts in your application's composer.json file:

{
    "scripts": {
        "post-update-cmd": [
            "@php artisan canvas:publish --ansi"
        ]
    }
}

Contributing

Thank you for considering contributing to Canvas! The contribution guide can be found here.

Testing

Run the tests with:

composer test

Troubleshooting

If you're running into problems, feel free to open a new issue or check the Discussions forum to see if anyone else has run into something similar.

Credits

Download Details:

Author: Austintoddj
Source Code: https://github.com/austintoddj/canvas 
License: MIT license

#laravel #blog #platform #canvas 

Canvas: A Laravel Publishing Platform

Wordcloud2.js: Tag Cloud/Wordle Presentation on 2D Canvas Or HTML

wordcloud2.js

Create a tag cloud/Wordle presentation on 2D canvas or HTML.

This library is a spin-off project from HTML5 Word Cloud.

Installation

npm install wordcloud

Simple usage

Download the latest wordcloud2.js file from the src folder in this repository.

Load wordcloud2.js script to the web page, and run:

WordCloud(document.getElementById('my_canvas'), { list: list } );

where list is an array that look like this: [['foo', 12], ['bar', 6]].

Options available, see API documentation for detail.

Contact & help

Please read through the API documentation and CONTRIBUTING.md before filing an issue or contact me via e-mail.

Algorithm

Before putting each word on the canvas, it is drawn on a separate canvas to read back the pixels to record is drawn spaces. With the information, wordcloud.js will then try to find a place to fit the word that is closest to the start point.

Testing

Tests are available with QUnit and grunt. To setup environment for testing, run npm install and manually install SlimerJS of your platform.

Use grunt test to ensure all options can be set without JavaScript error.

Use grunt compare --base-commit=gh-pages to compare your proposed fix with gh-pages branch.

Acknowledgement

The developer would like to thank Chad Jensen for sponsoring the work on image masking on the demo page.


Visit the demo page


Download Details:

Author: Timdream
Source Code: https://github.com/timdream/wordcloud2.js 
License: MIT license

#javascript #canvas #html 

Wordcloud2.js: Tag Cloud/Wordle Presentation on 2D Canvas Or HTML