Browse Source

Merge pull request #776 from LinusU/example-cleanup

Cleanup examples
v1.x
Linus Unnebäck 9 years ago
parent
commit
a297c79a1f
  1. 184
      examples/clock.js
  2. 47
      examples/crop.js
  3. 53
      examples/font.js
  4. 54
      examples/globalAlpha.js
  5. 44
      examples/gradients.js
  6. 28
      examples/grayscale-image.js
  7. 59
      examples/image-src.js
  8. 188
      examples/kraken.js
  9. 124
      examples/live-clock.js
  10. 57
      examples/multi-page-pdf.js
  11. 36
      examples/pango-glyphs.js
  12. 75
      examples/pdf-images.js
  13. 132
      examples/ray.js
  14. 49
      examples/resize.js
  15. 6
      examples/rhill-voronoi-core-min.js
  16. 33
      examples/small-pdf.js
  17. 33
      examples/small-svg.js
  18. 67
      examples/spark.js
  19. 44
      examples/state.js
  20. 66
      examples/text.js
  21. 264
      examples/voronoi.js
  22. 5
      package.json

184
examples/clock.js

@ -1,113 +1,113 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** function getX (angle) {
* Module dependencies. return -Math.sin(angle + Math.PI)
*/
var Canvas = require('../lib/canvas')
, canvas = new Canvas(320, 320)
, ctx = canvas.getContext('2d')
, fs = require('fs');
function getX(angle) {
return -Math.sin(angle + Math.PI);
} }
function getY(angle) {
return Math.cos(angle + Math.PI); function getY (angle) {
return Math.cos(angle + Math.PI)
} }
function clock(ctx){ function clock (ctx) {
var now = new Date(); var x, y, i
ctx.clearRect(0,0,320,320); var now = new Date()
ctx.save(); ctx.clearRect(0, 0, 320, 320)
ctx.translate(160,160);
ctx.beginPath(); ctx.save()
ctx.lineWidth = 14;
ctx.strokeStyle = '#325FA2'; ctx.translate(160, 160)
ctx.fillStyle = '#eeeeee'; ctx.beginPath()
ctx.arc(0,0,142,0,Math.PI*2,true); ctx.lineWidth = 14
ctx.stroke(); ctx.strokeStyle = '#325FA2'
ctx.fill(); ctx.fillStyle = '#eeeeee'
ctx.arc(0, 0, 142, 0, Math.PI * 2, true)
ctx.strokeStyle = '#000000'; ctx.stroke()
ctx.fill()
// Hour marks // Hour marks
ctx.lineWidth = 8; ctx.lineWidth = 8
for (var i=0;i<12;i++){ ctx.strokeStyle = '#000000'
var x = getX(Math.PI/6*i); for (i = 0; i < 12; i++) {
var y = getY(Math.PI/6*i); x = getX(Math.PI / 6 * i)
ctx.beginPath(); y = getY(Math.PI / 6 * i)
ctx.moveTo(x*100,y*100); ctx.beginPath()
ctx.lineTo(x*125,y*125); ctx.moveTo(x * 100, y * 100)
ctx.stroke(); ctx.lineTo(x * 125, y * 125)
ctx.stroke()
} }
// Minute marks // Minute marks
ctx.lineWidth = 5; ctx.lineWidth = 5
for (i=0;i<60;i++){ ctx.strokeStyle = '#000000'
if (i%5!=0) { for (i = 0; i < 60; i++) {
var x = getX(Math.PI/30*i); if (i % 5 !== 0) {
var y = getY(Math.PI/30*i); x = getX(Math.PI / 30 * i)
ctx.beginPath(); y = getY(Math.PI / 30 * i)
ctx.moveTo(x*117,y*117); ctx.beginPath()
ctx.lineTo(x*125,y*125); ctx.moveTo(x * 117, y * 117)
ctx.stroke(); ctx.lineTo(x * 125, y * 125)
ctx.stroke()
} }
} }
var sec = now.getSeconds(); var sec = now.getSeconds()
var min = now.getMinutes(); var min = now.getMinutes()
var hr = now.getHours(); var hr = now.getHours() % 12
hr = hr>=12 ? hr-12 : hr;
ctx.fillStyle = "black"; ctx.fillStyle = 'black'
// write Hours // Write hours
var x = getX(hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec); x = getX(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec)
var y = getY(hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec); y = getY(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec)
ctx.lineWidth = 14; ctx.lineWidth = 14
ctx.beginPath(); ctx.beginPath()
ctx.moveTo(x*-20,y*-20); ctx.moveTo(x * -20, y * -20)
ctx.lineTo(x*80,y*80); ctx.lineTo(x * 80, y * 80)
ctx.stroke(); ctx.stroke()
// write Minutes // Write minutes
var x = getX((Math.PI/30)*min + (Math.PI/1800)*sec); x = getX((Math.PI / 30) * min + (Math.PI / 1800) * sec)
var y = getY((Math.PI/30)*min + (Math.PI/1800)*sec); y = getY((Math.PI / 30) * min + (Math.PI / 1800) * sec)
ctx.lineWidth = 10; ctx.lineWidth = 10
ctx.beginPath(); ctx.beginPath()
ctx.moveTo(x*-28,y*-28); ctx.moveTo(x * -28, y * -28)
ctx.lineTo(x*112,y*112); ctx.lineTo(x * 112, y * 112)
ctx.stroke(); ctx.stroke()
// Write seconds // Write seconds
var x = getX(sec * Math.PI/30); x = getX(sec * Math.PI / 30)
var y = getY(sec * Math.PI/30); y = getY(sec * Math.PI / 30)
ctx.strokeStyle = "#D40000"; ctx.strokeStyle = '#D40000'
ctx.fillStyle = "#D40000"; ctx.fillStyle = '#D40000'
ctx.lineWidth = 6; ctx.lineWidth = 6
ctx.beginPath(); ctx.beginPath()
ctx.moveTo(x*-30,y*-30); ctx.moveTo(x * -30, y * -30)
ctx.lineTo(x*83,y*83); ctx.lineTo(x * 83, y * 83)
ctx.stroke(); ctx.stroke()
ctx.beginPath(); ctx.beginPath()
ctx.arc(0,0,10,0,Math.PI*2,true); ctx.arc(0, 0, 10, 0, Math.PI * 2, true)
ctx.fill(); ctx.fill()
ctx.beginPath(); ctx.beginPath()
ctx.arc(x*95,y*95,10,0,Math.PI*2,true); ctx.arc(x * 95, y * 95, 10, 0, Math.PI * 2, true)
ctx.stroke(); ctx.stroke()
ctx.fillStyle = "#555"; ctx.fillStyle = '#555'
ctx.arc(0,0,3,0,Math.PI*2,true); ctx.arc(0, 0, 3, 0, Math.PI * 2, true)
ctx.fill(); ctx.fill()
ctx.restore(); ctx.restore()
} }
clock(ctx); module.exports = clock
var out = fs.createWriteStream(__dirname + '/clock.png') if (require.main === module) {
, stream = canvas.createPNGStream(); var canvas = new Canvas(320, 320)
var ctx = canvas.getContext('2d')
stream.on('data', function(chunk){ clock(ctx)
out.write(chunk);
}); canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'clock.png')))
}

47
examples/crop.js

@ -1,36 +1,29 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var Image = Canvas.Image
* Module dependencies. var img = new Image()
*/
var Canvas = require('../lib/canvas') img.onerror = function (err) {
, Image = Canvas.Image throw err
, fs = require('fs'); }
var img = new Image; img.onload = function () {
img.onerror = function(err){
throw err;
};
img.onload = function(){
var w = img.width / 2 var w = img.width / 2
, h = img.height / 2 var h = img.height / 2
, canvas = new Canvas(w, h) var canvas = new Canvas(w, h)
, ctx = canvas.getContext('2d'); var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, w, h, 0, 0, w, h);
var out = fs.createWriteStream(__dirname + '/crop.jpg'); ctx.drawImage(img, 0, 0, w, h, 0, 0, w, h)
var out = fs.createWriteStream(path.join(__dirname, 'crop.png'))
var stream = canvas.createJPEGStream({ var stream = canvas.createJPEGStream({
bufsize : 2048, bufsize: 2048,
quality : 80 quality: 80
}); })
stream.pipe(out);
};
img.src = __dirname + '/images/squid.png';
stream.pipe(out)
}
img.src = path.join(__dirname, 'images', 'squid.png')

53
examples/font.js

@ -1,50 +1,39 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var Font = Canvas.Font
* Module dependencies.
*/
var Canvas = require('../lib/canvas')
, canvas = new Canvas(320, 320)
, Font = Canvas.Font
, ctx = canvas.getContext('2d')
, fs = require('fs')
, path = require("path");
if (!Font) { if (!Font) {
throw new Error('Need to compile with font support'); throw new Error('Need to compile with font support')
} }
function fontFile(name) { function fontFile (name) {
return path.join(__dirname, '/pfennigFont/', name); return path.join(__dirname, '/pfennigFont/', name)
} }
var pfennigFont = new Font('pfennigFont', fontFile('Pfennig.ttf')); var pfennigFont = new Font('pfennigFont', fontFile('Pfennig.ttf'))
pfennigFont.addFace(fontFile('PfennigBold.ttf'), 'bold'); pfennigFont.addFace(fontFile('PfennigBold.ttf'), 'bold')
pfennigFont.addFace(fontFile('PfennigItalic.ttf'), 'normal', 'italic'); pfennigFont.addFace(fontFile('PfennigItalic.ttf'), 'normal', 'italic')
pfennigFont.addFace(fontFile('PfennigBoldItalic.ttf'), 'bold', 'italic'); pfennigFont.addFace(fontFile('PfennigBoldItalic.ttf'), 'bold', 'italic')
var canvas = new Canvas(320, 320) var canvas = new Canvas(320, 320)
var ctx = canvas.getContext('2d') var ctx = canvas.getContext('2d')
// Tell the ctx to use the font. // Tell the ctx to use the font.
ctx.addFont(pfennigFont); ctx.addFont(pfennigFont)
ctx.font = 'normal normal 50px Helvetica';
ctx.fillText('Quo Vaids?', 0, 70); ctx.font = 'normal normal 50px Helvetica'
ctx.font = 'bold 50px pfennigFont'; ctx.fillText('Quo Vaids?', 0, 70)
ctx.fillText('Quo Vaids?', 0, 140);
ctx.font = 'italic 50px pfennigFont'; ctx.font = 'bold 50px pfennigFont'
ctx.fillText('Quo Vaids?', 0, 210); ctx.fillText('Quo Vaids?', 0, 140)
ctx.font = 'bold italic 50px pfennigFont'; ctx.font = 'italic 50px pfennigFont'
ctx.fillText('Quo Vaids?', 0, 280); ctx.fillText('Quo Vaids?', 0, 210)
var out = fs.createWriteStream(__dirname + '/font.png'); ctx.font = 'bold italic 50px pfennigFont'
var stream = canvas.createPNGStream(); ctx.fillText('Quo Vaids?', 0, 280)
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'font.png')))
out.write(chunk);
});

54
examples/globalAlpha.js

@ -1,36 +1,32 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(150, 150)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
ctx.fillStyle = '#FD0'
var Canvas = require('../lib/canvas') ctx.fillRect(0, 0, 75, 75)
, canvas = new Canvas(150, 150)
, ctx = canvas.getContext('2d') ctx.fillStyle = '#6C0'
, fs = require('fs'); ctx.fillRect(75, 0, 75, 75)
ctx.fillStyle = '#FD0'; ctx.fillStyle = '#09F)'
ctx.fillRect(0,0,75,75); ctx.fillRect(0, 75, 75, 75)
ctx.fillStyle = '#6C0';
ctx.fillRect(75,0,75,75); ctx.fillStyle = '#F30'
ctx.fillStyle = '#09F)'; ctx.fillRect(75, 75, 150, 150)
ctx.fillRect(0,75,75,75);
ctx.fillStyle = '#F30'; ctx.fillStyle = '#FFF'
ctx.fillRect(75,75,150,150);
ctx.fillStyle = '#FFF';
// set transparency value // set transparency value
ctx.globalAlpha = 0.2; ctx.globalAlpha = 0.2
// Draw semi transparent circles // Draw semi transparent circles
for (i=0;i<7;i++){ for (var i = 0; i < 7; i++) {
ctx.beginPath(); ctx.beginPath()
ctx.arc(75,75,10+10*i,0,Math.PI*2,true); ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true)
ctx.fill(); ctx.fill()
} }
var out = fs.createWriteStream(__dirname + '/globalAlpha.png') canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'globalAlpha.png')))
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){
out.write(chunk);
});

44
examples/gradients.js

@ -1,35 +1,27 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(320, 320)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas')
, canvas = new Canvas(320, 320)
, ctx = canvas.getContext('2d')
, fs = require('fs');
// Create gradients // Create gradients
var lingrad = ctx.createLinearGradient(0,0,0,150); var lingrad = ctx.createLinearGradient(0, 0, 0, 150)
lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0, '#00ABEB')
lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#fff')
lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(0.5, '#26C000')
lingrad.addColorStop(1, '#fff'); lingrad.addColorStop(1, '#fff')
var lingrad2 = ctx.createLinearGradient(0,50,0,95); var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95)
lingrad2.addColorStop(0.5, '#000'); lingrad2.addColorStop(0.5, '#000')
lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); lingrad2.addColorStop(1, 'rgba(0,0,0,0)')
// assign gradients to fill and stroke styles // assign gradients to fill and stroke styles
ctx.fillStyle = lingrad; ctx.fillStyle = lingrad
ctx.strokeStyle = lingrad2; ctx.strokeStyle = lingrad2
// draw shapes // draw shapes
ctx.fillRect(10,10,130,130); ctx.fillRect(10, 10, 130, 130)
ctx.strokeRect(50,50,50,50); ctx.strokeRect(50, 50, 50, 50)
var out = fs.createWriteStream(__dirname + '/gradients.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'gradients.png')))
out.write(chunk);
});

28
examples/grayscale-image.js

@ -1,22 +1,14 @@
/** var fs = require('fs')
* Passing grayscale image through canvas. Image should remain a gray square. var path = require('path')
* If image is distorted with lines, then grayscale images are being distorted. var Canvas = require('..')
*/
var Canvas = require('../lib/canvas')
, Image = Canvas.Image
, canvas = new Canvas(288, 288)
, ctx = canvas.getContext('2d')
, fs = require('fs');
var grayScaleImage = fs.readFileSync(__dirname + '/images/grayscaleImage.jpg'); var Image = Canvas.Image
img = new Image; var canvas = new Canvas(288, 288)
img.src = grayScaleImage; var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0); var img = new Image()
img.src = fs.readFileSync(path.join(__dirname, 'images', 'grayscaleImage.jpg'))
var out = fs.createWriteStream(__dirname + '/passedThroughGrayscale.jpg') ctx.drawImage(img, 0, 0)
, stream = canvas.createJPEGStream();
stream.on('data', function(chunk){ canvas.createJPEGStream().pipe(fs.createWriteStream(path.join(__dirname, 'passedThroughGrayscale.jpg')))
out.write(chunk);
});

59
examples/image-src.js

@ -1,45 +1,36 @@
var fs = require('fs')
var path = require(path)
var Canvas = require('..')
/** var Image = Canvas.Image
* Module dependencies. var canvas = new Canvas(200, 200)
*/ var ctx = canvas.getContext('2d')
var Canvas = require('../lib/canvas') ctx.fillRect(0, 0, 150, 150)
, Image = Canvas.Image ctx.save()
, canvas = new Canvas(200, 200)
, ctx = canvas.getContext('2d')
, fs = require('fs');
ctx.fillRect(0,0,150,150);
ctx.save();
ctx.fillStyle = '#09F' ctx.fillStyle = '#09F'
ctx.fillRect(15,15,120,120); ctx.fillRect(15, 15, 120, 120)
ctx.save(); ctx.save()
ctx.fillStyle = '#FFF' ctx.fillStyle = '#FFF'
ctx.globalAlpha = 0.5; ctx.globalAlpha = 0.5
ctx.fillRect(30,30,90,90); ctx.fillRect(30, 30, 90, 90)
ctx.restore();
ctx.fillRect(45,45,60,60);
ctx.restore(); ctx.restore()
ctx.fillRect(60,60,30,30); ctx.fillRect(45, 45, 60, 60)
var img = new Image; ctx.restore()
img.src = canvas.toBuffer(); ctx.fillRect(60, 60, 30, 30)
ctx.drawImage(img, 0, 0, 50, 50);
ctx.drawImage(img, 50, 0, 50, 50);
ctx.drawImage(img, 100, 0, 50, 50);
var squid = fs.readFileSync(__dirname + '/images/squid.png'); var img = new Image()
img = new Image; img.src = canvas.toBuffer()
img.src = squid; ctx.drawImage(img, 0, 0, 50, 50)
ctx.drawImage(img, 30, 50, img.width / 4, img.height / 4); ctx.drawImage(img, 50, 0, 50, 50)
ctx.drawImage(img, 100, 0, 50, 50)
var out = fs.createWriteStream(__dirname + '/image-src.png') img = new Image()
, stream = canvas.createPNGStream(); img.src = fs.readFileSync(path.join(__dirname, 'images', 'squid.png'))
ctx.drawImage(img, 30, 50, img.width / 4, img.height / 4)
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'image-src.png')))
out.write(chunk);
});

188
examples/kraken.js

@ -1,98 +1,104 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var Image = Canvas.Image
* Module dependencies. var canvas = new Canvas(400, 267)
*/ var ctx = canvas.getContext('2d')
var Canvas = require('../lib/canvas') var img = new Image()
, Image = Canvas.Image
, canvas = new Canvas(400, 267) img.onload = function () {
, ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0)
, fs = require('fs');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src = __dirname + '/images/squid.png';
var sigma = 10; // radius
var kernel, kernelSize, kernelSum;
buildKernel();
function buildKernel() {
var ss = sigma * sigma;
var factor = 2 * Math.PI * ss;
kernel = [];
kernel.push([]);
var i = 0, j;
do {
var g = Math.exp(-(i * i) / (2 * ss)) / factor;
if (g < 1e-3) break;
kernel[0].push(g);
++i;
} while (i < 7);
kernelSize = i;
for (j = 1; j < kernelSize; ++j) {
kernel.push([]);
for (i = 0; i < kernelSize; ++i) {
var g = Math.exp(-(i * i + j * j) / (2 * ss)) / factor;
kernel[j].push(g);
}
}
kernelSum = 0;
for (j = 1 - kernelSize; j < kernelSize; ++j) {
for (i = 1 - kernelSize; i < kernelSize; ++i) {
kernelSum += kernel[Math.abs(j)][Math.abs(i)];
}
}
} }
function blurTest() { img.src = path.join(__dirname, 'images', 'squid.png')
console.log('... running');
var sigma = 10 // radius
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); var kernel, kernelSize, kernelSum
var width = imgData.width, height = imgData.height;
var data = imgData.data; function buildKernel () {
var i, j, g
var len = data.length; var ss = sigma * sigma
var startTime = (new Date()).getTime(); var factor = 2 * Math.PI * ss
for (var y = 0; y < height; ++y) { kernel = [[]]
for (var x = 0; x < width; ++x) {
var r = 0, g = 0, b = 0, a = 0; i = 0
for (j = 1 - kernelSize; j < kernelSize; ++j) { do {
if (y + j < 0 || y + j >= height) continue; g = Math.exp(-(i * i) / (2 * ss)) / factor
for (i = 1 - kernelSize; i < kernelSize; ++i) { if (g < 1e-3) break
if (x + i < 0 || x + i >= width) continue; kernel[0].push(g)
r += data[4 * ((y + j) * width + (x + i)) + 0] * kernel[Math.abs(j)][Math.abs(i)]; ++i
g += data[4 * ((y + j) * width + (x + i)) + 1] * kernel[Math.abs(j)][Math.abs(i)]; } while (i < 7)
b += data[4 * ((y + j) * width + (x + i)) + 2] * kernel[Math.abs(j)][Math.abs(i)];
a += data[4 * ((y + j) * width + (x + i)) + 3] * kernel[Math.abs(j)][Math.abs(i)]; kernelSize = i
} for (j = 1; j < kernelSize; ++j) {
} kernel.push([])
data[4 * (y * width + x) + 0] = r / kernelSum; for (i = 0; i < kernelSize; ++i) {
data[4 * (y * width + x) + 1] = g / kernelSum; g = Math.exp(-(i * i + j * j) / (2 * ss)) / factor
data[4 * (y * width + x) + 2] = b / kernelSum; kernel[j].push(g)
data[4 * (y * width + x) + 3] = a / kernelSum; }
} }
}
var finishTime = Date.now() - startTime; kernelSum = 0
for (var i = 0; i < data.length; i++) { for (j = 1 - kernelSize; j < kernelSize; ++j) {
imgData.data[i] = data[i]; for (i = 1 - kernelSize; i < kernelSize; ++i) {
} kernelSum += kernel[Math.abs(j)][Math.abs(i)]
//imgData.data = data; }
ctx.putImageData(imgData, 0, 0); }
console.log('... finished in %dms', finishTime);
} }
blurTest(); function blurTest () {
var x, y, i, j
var r, g, b, a
console.log('... running')
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
var data = imgData.data
var width = imgData.width
var height = imgData.height
var startTime = (new Date()).getTime()
for (y = 0; y < height; ++y) {
for (x = 0; x < width; ++x) {
r = 0
g = 0
b = 0
a = 0
for (j = 1 - kernelSize; j < kernelSize; ++j) {
if (y + j < 0 || y + j >= height) continue
for (i = 1 - kernelSize; i < kernelSize; ++i) {
if (x + i < 0 || x + i >= width) continue
r += data[4 * ((y + j) * width + (x + i)) + 0] * kernel[Math.abs(j)][Math.abs(i)]
g += data[4 * ((y + j) * width + (x + i)) + 1] * kernel[Math.abs(j)][Math.abs(i)]
b += data[4 * ((y + j) * width + (x + i)) + 2] * kernel[Math.abs(j)][Math.abs(i)]
a += data[4 * ((y + j) * width + (x + i)) + 3] * kernel[Math.abs(j)][Math.abs(i)]
}
}
data[4 * (y * width + x) + 0] = r / kernelSum
data[4 * (y * width + x) + 1] = g / kernelSum
data[4 * (y * width + x) + 2] = b / kernelSum
data[4 * (y * width + x) + 3] = a / kernelSum
}
}
var finishTime = Date.now() - startTime
for (i = 0; i < data.length; i++) {
imgData.data[i] = data[i]
}
ctx.putImageData(imgData, 0, 0)
console.log('... finished in %dms', finishTime)
}
var out = fs.createWriteStream(__dirname + '/kraken.png') buildKernel()
, stream = canvas.createPNGStream(); blurTest()
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'kraken.png')))
out.write(chunk);
});

124
examples/live-clock.js

@ -1,113 +1,19 @@
var http = require('http')
var Canvas = require('..')
/** var clock = require('./clock')
* Module dependencies.
*/
var Canvas = require('../lib/canvas') var canvas = new Canvas(320, 320)
, canvas = new Canvas(320, 320) var ctx = canvas.getContext('2d')
, ctx = canvas.getContext('2d')
, http = require('http');
function getX(angle) {
return -Math.sin(angle + Math.PI);
}
function getY(angle) {
return Math.cos(angle + Math.PI);
}
function clock(ctx){
var now = new Date();
ctx.clearRect(0,0,320,320);
ctx.save();
ctx.translate(160,160);
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = '#325FA2';
ctx.fillStyle = '#eeeeee';
ctx.arc(0,0,142,0,Math.PI*2,true);
ctx.stroke();
ctx.fill();
ctx.strokeStyle = '#000000';
// Hour marks
ctx.lineWidth = 8;
for (var i=0;i<12;i++){
var x = getX(Math.PI/6*i);
var y = getY(Math.PI/6*i);
ctx.beginPath();
ctx.moveTo(x*100,y*100);
ctx.lineTo(x*125,y*125);
ctx.stroke();
}
// Minute marks
ctx.lineWidth = 5;
for (i=0;i<60;i++){
if (i%5!=0) {
var x = getX(Math.PI/30*i);
var y = getY(Math.PI/30*i);
ctx.beginPath();
ctx.moveTo(x*117,y*117);
ctx.lineTo(x*125,y*125);
ctx.stroke();
}
}
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
hr = hr>=12 ? hr-12 : hr;
ctx.fillStyle = "black";
// write Hours
var x = getX(hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec);
var y = getY(hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec);
ctx.lineWidth = 14;
ctx.beginPath();
ctx.moveTo(x*-20,y*-20);
ctx.lineTo(x*80,y*80);
ctx.stroke();
// write Minutes
var x = getX((Math.PI/30)*min + (Math.PI/1800)*sec);
var y = getY((Math.PI/30)*min + (Math.PI/1800)*sec);
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(x*-28,y*-28);
ctx.lineTo(x*112,y*112);
ctx.stroke();
// Write seconds
var x = getX(sec * Math.PI/30);
var y = getY(sec * Math.PI/30);
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(x*-30,y*-30);
ctx.lineTo(x*83,y*83);
ctx.stroke();
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true);
ctx.fill();
ctx.beginPath();
ctx.arc(x*95,y*95,10,0,Math.PI*2,true);
ctx.stroke();
ctx.fillStyle = "#555";
ctx.arc(0,0,3,0,Math.PI*2,true);
ctx.fill();
ctx.restore();
}
http.createServer(function (req, res) { http.createServer(function (req, res) {
clock(ctx); clock(ctx)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('' res.writeHead(200, { 'Content-Type': 'text/html' })
+ '<meta http-equiv="refresh" content="1;" />' res.end(
+ '<img src="' + canvas.toDataURL() + '" />'); '<meta http-equiv="refresh" content="1;" />' +
}).listen(3000); '<img src="' + canvas.toDataURL() + '" />'
console.log('Server started on port 3000'); )
}).listen(3000, function () {
console.log('Server started on port 3000')
})

57
examples/multi-page-pdf.js

@ -1,39 +1,42 @@
var fs = require('fs')
var Canvas = require('..')
var Canvas = require('../') var canvas = new Canvas(500, 500, 'pdf')
, canvas = new Canvas(500, 500, 'pdf') var ctx = canvas.getContext('2d')
, ctx = canvas.getContext('2d')
, fs = require('fs');
var x, y; var x, y
function reset() { function reset () {
x = 50; x = 50
y = 80; y = 80
} }
function h1(str) { function h1 (str) {
ctx.font = '22px Helvetica'; ctx.font = '22px Helvetica'
ctx.fillText(str, x, y); ctx.fillText(str, x, y)
} }
function p(str) { function p (str) {
ctx.font = '10px Arial'; ctx.font = '10px Arial'
ctx.fillText(str, x, y += 20); ctx.fillText(str, x, (y += 20))
} }
reset(); reset()
h1('PDF demo'); h1('PDF demo')
p('Multi-page PDF demonstration'); p('Multi-page PDF demonstration')
ctx.addPage(); ctx.addPage()
reset(); reset()
h1('Page #2'); h1('Page #2')
p('This is the second page'); p('This is the second page')
ctx.addPage(); ctx.addPage()
reset(); reset()
h1('Page #3'); h1('Page #3')
p('This is the third page'); p('This is the third page')
fs.writeFile('out.pdf', canvas.toBuffer()); fs.writeFile('out.pdf', canvas.toBuffer(), function (err) {
console.log('created out.pdf'); if (err) throw err
console.log('created out.pdf')
})

36
examples/pango-glyphs.js

@ -1,30 +1,22 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(400, 100)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas') ctx.globalAlpha = 1
, canvas = new Canvas(400, 100) ctx.font = 'normal 16px Impact'
, ctx = canvas.getContext('2d')
, fs = require('fs');
ctx.globalAlpha = 1; ctx.textBaseline = 'top'
ctx.font = 'normal 16px Impact';
ctx.textBaseline = 'top';
// Note this demo depends node-canvas being installed with pango support, // Note this demo depends node-canvas being installed with pango support,
// and your system having installed fonts supporting the glyphs. // and your system having installed fonts supporting the glyphs.
ctx.fillStyle = '#000'; ctx.fillStyle = '#000'
ctx.fillText("English: Some text in Impact.", 10, 10); ctx.fillText('English: Some text in Impact.', 10, 10)
ctx.fillText("Japanese: 図書館の中では、静かにする。", 10, 30); ctx.fillText('Japanese: 図書館の中では、静かにする。', 10, 30)
ctx.fillText("Arabic: اللغة العربية هي أكثر اللغات تحدثا ضمن", 10, 50); ctx.fillText('Arabic: اللغة العربية هي أكثر اللغات تحدثا ضمن', 10, 50)
ctx.fillText("Korean: 모타는사라미 못하는 사람이", 10, 70); ctx.fillText('Korean: 모타는사라미 못하는 사람이', 10, 70)
var out = fs.createWriteStream(__dirname + '/pango-glyphs.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'pango-glyphs.png')))
out.write(chunk);
});

75
examples/pdf-images.js

@ -1,47 +1,50 @@
var fs = require('fs')
var Canvas = require('..')
var Canvas = require('../') var Image = Canvas.Image
, Image = Canvas.Image var canvas = new Canvas(500, 500, 'pdf')
, canvas = new Canvas(500, 500, 'pdf') var ctx = canvas.getContext('2d')
, ctx = canvas.getContext('2d')
, fs = require('fs');
var x, y; var x, y
function reset() { function reset () {
x = 50; x = 50
y = 80; y = 80
} }
function h1(str) { function h1 (str) {
ctx.font = '22px Helvetica'; ctx.font = '22px Helvetica'
ctx.fillText(str, x, y); ctx.fillText(str, x, y)
} }
function p(str) { function p (str) {
ctx.font = '10px Arial'; ctx.font = '10px Arial'
ctx.fillText(str, x, y += 20); ctx.fillText(str, x, (y += 20))
} }
function img(src) { function img (src) {
var img = new Image; var img = new Image()
img.src = src; img.src = src
ctx.drawImage(img, x, y += 20); ctx.drawImage(img, x, (y += 20))
y += img.height; y += img.height
} }
reset(); reset()
h1('PDF image demo'); h1('PDF image demo')
p('This is an image embedded in a PDF'); p('This is an image embedded in a PDF')
img('examples/images/squid.png'); img('examples/images/squid.png')
p('Figure 1.0 - Some squid thing'); p('Figure 1.0 - Some squid thing')
ctx.addPage(); ctx.addPage()
reset(); reset()
h1('Lime cat'); h1('Lime cat')
p('This is a pretty sweet cat'); p('This is a pretty sweet cat')
img('examples/images/lime-cat.jpg'); img('examples/images/lime-cat.jpg')
p('Figure 1.1 - Lime cat is awesome'); p('Figure 1.1 - Lime cat is awesome')
ctx.addPage(); ctx.addPage()
fs.writeFile('out.pdf', canvas.toBuffer()); fs.writeFile('out.pdf', canvas.toBuffer(), function (err) {
console.log('created out.pdf'); if (err) throw err
console.log('created out.pdf')
})

132
examples/ray.js

@ -1,85 +1,85 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(243 * 4, 243)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas') function render (level) {
, canvas = new Canvas(243 * 4, 243) ctx.fillStyle = getPointColour(122, 122)
, ctx = canvas.getContext('2d') ctx.fillRect(0, 0, 240, 240)
, fs = require('fs'); renderLevel(level, 81, 0)
function render(level){
ctx.fillStyle = getPointColour(122,122);
ctx.fillRect(0,0,240,240);
renderLevel(level,81,0);
} }
function renderLevel(minimumLevel,level,y){ function renderLevel (minimumLevel, level, y) {
for (var x=0; x < 243 / level; ++x) { var x
drawBlock(x,y,level);
for (x = 0; x < 243 / level; ++x) {
drawBlock(x, y, level)
} }
for (var x=0; x < 243 / level; x+=3){ for (x = 0; x < 243 / level; x += 3) {
drawBlock(x,y+1,level); drawBlock(x, y + 1, level)
drawBlock(x+2,y+1,level); drawBlock(x + 2, y + 1, level)
} }
for (var x=0; x < 243 / level; ++x){ for (x = 0; x < 243 / level; ++x) {
drawBlock(x,y+2,level); drawBlock(x, y + 2, level)
} }
if ((y += 3) >= 243 / level){ if ((y += 3) >= 243 / level) {
y=0; y = 0
level /= 3; level /= 3
} }
if (level >= minimumLevel){ if (level >= minimumLevel) {
renderLevel(minimumLevel, level, y); renderLevel(minimumLevel, level, y)
} }
} }
function drawBlock(x,y,level){ function drawBlock (x, y, level) {
ctx.fillStyle = getPointColour( ctx.fillStyle = getPointColour(
x * level + (level-1) / 2 x * level + (level - 1) / 2,
, y * level + (level-1) / 2); y * level + (level - 1) / 2
)
ctx.fillRect( ctx.fillRect(
x * level x * level,
, y * level y * level,
, level level,
, level level
); )
} }
function getPointColour(x,y){ function getPointColour (x, y) {
x= x / 121.5 - 1; x = x / 121.5 - 1
y= -y / 121.5 + 1; y = -y / 121.5 + 1
var x2y2 = x * x + y * y;
if (x2y2 > 1){ var x2y2 = x * x + y * y
return '#000'; if (x2y2 > 1) {
} else { return '#000'
var root = Math.sqrt(1 - x2y2); }
var x3d = x * 0.7071067812 + root / 2 - y / 2;
var y3d = x * 0.7071067812 - root / 2 + y / 2; var root = Math.sqrt(1 - x2y2)
var z3d = 0.7071067812 * root + 0.7071067812 * y; var x3d = x * 0.7071067812 + root / 2 - y / 2
var brightness= -x / 2 + root * 0.7071067812 + y / 2; var y3d = x * 0.7071067812 - root / 2 + y / 2
if (brightness < 0) brightness = 0; var z3d = 0.7071067812 * root + 0.7071067812 * y
return '' var brightness = -x / 2 + root * 0.7071067812 + y / 2
+ 'rgb(' + Math.round(brightness * 127.5 * (1 - y3d)) if (brightness < 0) brightness = 0
+ ',' + Math.round(brightness * 127.5 * (x3d + 1))
+ ',' + Math.round(brightness * 127.5 * (z3d + 1)) var r = Math.round(brightness * 127.5 * (1 - y3d))
+ ')' var g = Math.round(brightness * 127.5 * (x3d + 1))
; var b = Math.round(brightness * 127.5 * (z3d + 1))
}
return 'rgb(' + r + ', ' + g + ', ' + b + ')'
} }
var start = new Date; var start = new Date()
render(10);
ctx.translate(243,0); render(10)
render(6); ctx.translate(243, 0)
ctx.translate(243,0); render(6)
render(3); ctx.translate(243, 0)
ctx.translate(243,0); render(3)
render(1); ctx.translate(243, 0)
console.log('Rendered in %s seconds', (new Date - start) / 1000); render(1)
console.log('Rendered in %s seconds', (new Date() - start) / 1000)
canvas.toBuffer(function(err, buf){ canvas.pngStream().pipe(fs.createWriteStream(path.join(__dirname, 'ray.png')))
if (err) throw err;
fs.writeFile(__dirname + '/ray.png', buf);
});

49
examples/resize.js

@ -1,34 +1,31 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var Image = Canvas.Image
* Module dependencies.
*/
var Canvas = require('../lib/canvas') var img = new Image()
, Image = Canvas.Image var start = new Date()
, fs = require('fs');
var img = new Image img.onerror = function (err) {
, start = new Date; throw err
}
img.onerror = function(err){ img.onload = function () {
throw err; var width = 100
}; var height = 100
var canvas = new Canvas(width, height)
var ctx = canvas.getContext('2d')
var out = fs.createWriteStream(path.join(__dirname, 'resize.png'))
img.onload = function(){ ctx.imageSmoothingEnabled = true
var width = 100; ctx.drawImage(img, 0, 0, width, height)
var height = 100;
var canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = true; canvas.pngStream().pipe(out)
ctx.drawImage(img, 0, 0, width, height);
canvas.toBuffer(function(err, buf){ out.on('finish', function () {
fs.writeFile(__dirname + '/resize.png', buf, function(){ console.log('Resized and saved in %dms', new Date() - start)
console.log('Resized and saved in %dms', new Date - start); })
}); }
});
};
img.src = process.argv[2] || __dirname + '/images/squid.png';
img.src = (process.argv[2] || path.join(__dirname, 'images', 'squid.png'))

6
examples/rhill-voronoi-core-min.js

File diff suppressed because one or more lines are too long

33
examples/small-pdf.js

@ -1,22 +1,25 @@
var fs = require('fs')
var Canvas = require('..')
var Canvas = require('../') var canvas = new Canvas(400, 200, 'pdf')
, canvas = new Canvas(400, 200, 'pdf') var ctx = canvas.getContext('2d')
, ctx = canvas.getContext('2d')
, fs = require('fs');
var y = 80 var y = 80
, x = 50; var x = 50
ctx.font = '22px Helvetica'; ctx.font = '22px Helvetica'
ctx.fillText('node-canvas pdf', x, y); ctx.fillText('node-canvas pdf', x, y)
ctx.font = '10px Arial'; ctx.font = '10px Arial'
ctx.fillText('Just a quick example of PDFs with node-canvas', x, y += 20); ctx.fillText('Just a quick example of PDFs with node-canvas', x, (y += 20))
ctx.globalAlpha = .5; ctx.globalAlpha = 0.5
ctx.fillRect(x, y += 20, 10, 10); ctx.fillRect(x, (y += 20), 10, 10)
ctx.fillRect(x += 20, y, 10, 10); ctx.fillRect((x += 20), y, 10, 10)
ctx.fillRect(x += 20, y, 10, 10); ctx.fillRect((x += 20), y, 10, 10)
fs.writeFile('out.pdf', canvas.toBuffer()); fs.writeFile('out.pdf', canvas.toBuffer(), function (err) {
console.log('created out.pdf'); if (err) throw err
console.log('created out.pdf')
})

33
examples/small-svg.js

@ -1,22 +1,25 @@
var fs = require('fs')
var Canvas = require('..')
var Canvas = require('../') var canvas = new Canvas(400, 200, 'svg')
, canvas = new Canvas(400, 200, 'svg') var ctx = canvas.getContext('2d')
, ctx = canvas.getContext('2d')
, fs = require('fs');
var y = 80 var y = 80
, x = 50; var x = 50
ctx.font = '22px Helvetica'; ctx.font = '22px Helvetica'
ctx.fillText('node-canvas SVG', x, y); ctx.fillText('node-canvas SVG', x, y)
ctx.font = '10px Arial'; ctx.font = '10px Arial'
ctx.fillText('Just a quick example of SVGs with node-canvas', x, y += 20); ctx.fillText('Just a quick example of SVGs with node-canvas', x, (y += 20))
ctx.globalAlpha = .5; ctx.globalAlpha = 0.5
ctx.fillRect(x, y += 20, 10, 10); ctx.fillRect(x, (y += 20), 10, 10)
ctx.fillRect(x += 20, y, 10, 10); ctx.fillRect((x += 20), y, 10, 10)
ctx.fillRect(x += 20, y, 10, 10); ctx.fillRect((x += 20), y, 10, 10)
fs.writeFile('out.svg', canvas.toBuffer()); fs.writeFile('out.svg', canvas.toBuffer(), function (err) {
console.log('created out.svg'); if (err) throw err
console.log('created out.svg')
})

67
examples/spark.js

@ -1,46 +1,33 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(40, 15)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
function spark (ctx, data) {
var Canvas = require('../lib/canvas')
, canvas = new Canvas(40, 15)
, ctx = canvas.getContext('2d')
, fs = require('fs');
Object.defineProperty(Array.prototype, 'max', {
get: function(){
var max = 0;
for (var i = 0, len = this.length; i < len; ++i) {
var n = this[i];
if (n > max) max = n;
}
return max;
}
});
function spark(ctx, data) {
var len = data.length var len = data.length
, pad = 1 var pad = 1
, width = ctx.canvas.width var width = ctx.canvas.width
, height = ctx.canvas.height var height = ctx.canvas.height
, barWidth = width / len var barWidth = width / len
, max = data.max; var max = Math.max.apply(null, data)
ctx.fillStyle = 'rgba(0,0,255,0.5)';
ctx.strokeStyle = 'red'; ctx.fillStyle = 'rgba(0,0,255,0.5)'
ctx.lineWidth = 1; ctx.strokeStyle = 'red'
data.forEach(function(n, i){ ctx.lineWidth = 1
data.forEach(function (n, i) {
var x = i * barWidth + pad var x = i * barWidth + pad
, y = height * (n / max) var y = height * (n / max)
ctx.lineTo(x, height - y);
ctx.fillRect(x, height, barWidth - pad, -y); ctx.lineTo(x, height - y)
}); ctx.fillRect(x, height, barWidth - pad, -y)
ctx.stroke(); })
ctx.stroke()
} }
spark(ctx, [1,2,4,5,10,4,2,5,4,3,3,2]); spark(ctx, [1, 2, 4, 5, 10, 4, 2, 5, 4, 3, 3, 2])
canvas.toBuffer(function(err, buf){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'spark.png')))
if (err) throw err;
fs.writeFile(__dirname + '/spark.png', buf);
});

44
examples/state.js

@ -1,33 +1,25 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(150, 150)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas') ctx.fillRect(0, 0, 150, 150) // Draw a rectangle with default settings
, canvas = new Canvas(150, 150) ctx.save() // Save the default state
, ctx = canvas.getContext('2d')
, fs = require('fs');
ctx.fillRect(0,0,150,150); // Draw a rectangle with default settings ctx.fillStyle = '#09F' // Make changes to the settings
ctx.save(); // Save the default state ctx.fillRect(15, 15, 120, 120) // Draw a rectangle with new settings
ctx.fillStyle = '#09F' // Make changes to the settings ctx.save() // Save the current state
ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings ctx.fillStyle = '#FFF' // Make changes to the settings
ctx.globalAlpha = 0.5
ctx.fillRect(30, 30, 90, 90) // Draw a rectangle with new settings
ctx.save(); // Save the current state ctx.restore() // Restore previous state
ctx.fillStyle = '#FFF' // Make changes to the settings ctx.fillRect(45, 45, 60, 60) // Draw a rectangle with restored settings
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90); // Draw a rectangle with new settings
ctx.restore(); // Restore previous state ctx.restore() // Restore original state
ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings ctx.fillRect(60, 60, 30, 30) // Draw a rectangle with restored settings
ctx.restore(); // Restore original state canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'state.png')))
ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings
var out = fs.createWriteStream(__dirname + '/state.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){
out.write(chunk);
});

66
examples/text.js

@ -1,50 +1,44 @@
var fs = require('fs')
var path = require('path')
var Canvas = require('..')
/** var canvas = new Canvas(200, 200)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas') ctx.globalAlpha = 0.2
, canvas = new Canvas(200, 200)
, ctx = canvas.getContext('2d')
, fs = require('fs');
ctx.globalAlpha = .2; ctx.strokeRect(0, 0, 200, 200)
ctx.lineTo(0, 100)
ctx.lineTo(200, 100)
ctx.stroke()
ctx.strokeRect(0,0,200,200); ctx.beginPath()
ctx.lineTo(0,100); ctx.lineTo(100, 0)
ctx.lineTo(200,100); ctx.lineTo(100, 200)
ctx.stroke(); ctx.stroke()
ctx.beginPath(); ctx.globalAlpha = 1
ctx.lineTo(100,0); ctx.font = 'normal 40px Impact, serif'
ctx.lineTo(100,200);
ctx.stroke();
ctx.globalAlpha = 1; ctx.rotate(0.5)
ctx.font = 'normal 40px Impact, serif'; ctx.translate(20, -40)
ctx.rotate(.5); ctx.lineWidth = 1
ctx.translate(20,-40); ctx.strokeStyle = '#ddd'
ctx.strokeText('Wahoo', 50, 100)
ctx.lineWidth = 1; ctx.fillStyle = '#000'
ctx.strokeStyle = '#ddd'; ctx.fillText('Wahoo', 49, 99)
ctx.strokeText("Wahoo", 50, 100);
ctx.fillStyle = '#000'; var m = ctx.measureText('Wahoo')
ctx.fillText("Wahoo", 49, 99);
var m = ctx.measureText("Wahoo"); ctx.strokeStyle = '#f00'
ctx.strokeStyle = '#f00'; ctx.strokeRect(
49 + m.actualBoundingBoxLeft,
ctx.strokeRect(49 + m.actualBoundingBoxLeft,
99 - m.actualBoundingBoxAscent, 99 - m.actualBoundingBoxAscent,
m.actualBoundingBoxRight - m.actualBoundingBoxLeft, m.actualBoundingBoxRight - m.actualBoundingBoxLeft,
m.actualBoundingBoxAscent + m.actualBoundingBoxDescent); m.actualBoundingBoxAscent + m.actualBoundingBoxDescent
)
var out = fs.createWriteStream(__dirname + '/text.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){ canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'text.png')))
out.write(chunk);
});

264
examples/voronoi.js

@ -1,140 +1,134 @@
var http = require('http')
var Canvas = require('..')
/** var canvas = new Canvas(1920, 1200)
* Module dependencies. var ctx = canvas.getContext('2d')
*/
var Canvas = require('../lib/canvas') var voronoiFactory = require('./rhill-voronoi-core-min')
, canvas = new Canvas(1920, 1200)
, ctx = canvas.getContext('2d')
, http = require('http')
, fs = require('fs');
var voronoiFactory = require('./rhill-voronoi-core-min.js');
http.createServer(function (req, res) { http.createServer(function (req, res) {
var x, y, v, iHalfedge
var voronoi = voronoiFactory() var voronoi = voronoiFactory()
, start = new Date; var start = new Date()
var bbox = { xl: 0, xr: canvas.width, yt: 0, yb: canvas.height }; var bbox = { xl: 0, xr: canvas.width, yt: 0, yb: canvas.height }
for (var i =0 ;i<340;i++) for (var i = 0; i < 340; i++) {
{ x = Math.random() * canvas.width
var x = Math.random()*canvas.width; y = Math.random() * canvas.height
var y = Math.random()*canvas.height; voronoi.addSites([{ x: x, y: y }])
voronoi.addSites([{x:x,y:y}]); }
};
var diagram = voronoi.compute(bbox); var diagram = voronoi.compute(bbox)
ctx.beginPath(); ctx.beginPath()
ctx.rect(0,0,canvas.width,canvas.height); ctx.rect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = '#fff'; ctx.fillStyle = '#fff'
ctx.fill(); ctx.fill()
ctx.strokeStyle = 'black'; ctx.strokeStyle = 'black'
ctx.stroke(); ctx.stroke()
// voronoi // voronoi
ctx.strokeStyle='rgba(255,255,255,0.5)'; ctx.strokeStyle = 'rgba(255,255,255,0.5)'
ctx.lineWidth = 4; ctx.lineWidth = 4
// edges // edges
var edges = diagram.edges; var edges = diagram.edges
var nEdges = edges.length; var nEdges = edges.length
var sites = diagram.sites; var sites = diagram.sites
var nSites = sites.length; var nSites = sites.length
for (var iSite=nSites-1; iSite>=0; iSite-=1) for (var iSite = nSites - 1; iSite >= 0; iSite -= 1) {
{ var site = sites[iSite]
site = sites[iSite]; ctx.rect(site.x - 0.5, site.y - 0.5, 1, 1)
ctx.rect(site.x-0.5,site.y-0.5,1,1);
var cell = diagram.cells[diagram.sites[iSite].id]
if (cell !== undefined) {
var halfedges = cell.halfedges
// ctx.stroke(); var nHalfedges = halfedges.length
var cell = diagram.cells[diagram.sites[iSite].id]; if (nHalfedges < 3) return
if (cell !== undefined) var minx = canvas.width
{ var miny = canvas.height
var halfedges = cell.halfedges; var maxx = 0
var nHalfedges = halfedges.length; var maxy = 0
if (nHalfedges < 3) {return;}
var minx = canvas.width; v = halfedges[0].getStartpoint()
var miny = canvas.height; ctx.beginPath()
var maxx = 0; ctx.moveTo(v.x, v.y)
var maxy = 0;
for (iHalfedge = 0; iHalfedge < nHalfedges; iHalfedge++) {
var v = halfedges[0].getStartpoint(); v = halfedges[iHalfedge].getEndpoint()
ctx.beginPath(); ctx.lineTo(v.x, v.y)
ctx.moveTo(v.x,v.y); if (v.x < minx) minx = v.x
if (v.y < miny) miny = v.y
for (var iHalfedge=0; iHalfedge<nHalfedges; iHalfedge++) if (v.x > maxx) maxx = v.x
{ if (v.y > maxy) maxy = v.y
v = halfedges[iHalfedge].getEndpoint(); }
ctx.lineTo(v.x,v.y);
if (v.x< minx) minx = v.x; var midx = (maxx + minx) / 2
if (v.y< miny) miny = v.y; var midy = (maxy + miny) / 2
if (v.x> maxx) maxx = v.x; var R = 0
if (v.y> maxy) maxy = v.y;
} for (iHalfedge = 0; iHalfedge < nHalfedges; iHalfedge++) {
var C = Math.floor(Math.random()*128 + 127).toString(); v = halfedges[iHalfedge].getEndpoint()
var dx = v.x - site.x
var dy = v.y - site.y
var midx = (maxx+minx)/2; var newR = Math.sqrt(dx * dx + dy * dy)
var midy = (maxy+miny)/2; if (newR > R) R = newR
var R = 0; }
for (var iHalfedge=0; iHalfedge<nHalfedges; iHalfedge++) midx = site.x
{ midy = site.y
v = halfedges[iHalfedge].getEndpoint();
var dx = v.x - site.x; var radgrad = ctx.createRadialGradient(midx + R * 0.3, midy - R * 0.3, 0, midx, midy, R)
var dy = v.y - site.y; radgrad.addColorStop(0, '#09760b')
var newR = Math.sqrt(dx*dx + dy*dy); radgrad.addColorStop(1.0, 'black')
if (newR >R) R = newR; ctx.fillStyle = radgrad
} ctx.fill()
midx = site.x;
midy = site.y; var radgrad2 = ctx.createRadialGradient(midx - R * 0.5, midy + R * 0.5, R * 0.1, midx, midy, R)
var radgrad = ctx.createRadialGradient(midx+R*0.3,midy-R*0.3,0,midx,midy,R); radgrad2.addColorStop(0, 'rgba(255,255,255,0.5)')
radgrad.addColorStop(0, "#09760b"); radgrad2.addColorStop(0.04, 'rgba(255,255,255,0.3)')
radgrad.addColorStop(1.0, "black"); radgrad2.addColorStop(0.05, 'rgba(255,255,255,0)')
ctx.fillStyle = radgrad2
ctx.fill()
ctx.fillStyle = radgrad;
ctx.fill(); var lingrad = ctx.createLinearGradient(minx, site.y, minx + 100, site.y - 20)
lingrad.addColorStop(0.0, 'rgba(255,255,255,0.5)')
var radgrad2 = ctx.createRadialGradient(midx-R*0.5,midy+R*0.5,R*0.1,midx,midy,R); lingrad.addColorStop(0.2, 'rgba(255,255,255,0.2)')
radgrad2.addColorStop(0, "rgba(255,255,255,0.5)"); lingrad.addColorStop(1.0, 'rgba(255,255,255,0)')
radgrad2.addColorStop(0.04, "rgba(255,255,255,0.3)"); ctx.fillStyle = lingrad
radgrad2.addColorStop(0.05, "rgba(255,255,255,0)"); ctx.fill()
}
}
ctx.fillStyle = radgrad2;
ctx.fill(); if (nEdges) {
var edge
var lingrad = ctx.createLinearGradient(minx, site.y, minx+100, site.y-20);
lingrad.addColorStop(0.0, "rgba(255,255,255,0.5)"); ctx.beginPath()
lingrad.addColorStop(0.2, "rgba(255,255,255,0.2)");
lingrad.addColorStop(1.0, "rgba(255,255,255,0)"); for (var iEdge = nEdges - 1; iEdge >= 0; iEdge -= 1) {
ctx.fillStyle = lingrad; edge = edges[iEdge]
ctx.fill(); v = edge.va
ctx.moveTo(v.x, v.y)
} v = edge.vb
ctx.lineTo(v.x, v.y)
} }
if (nEdges) ctx.stroke()
{ }
var edge, v;
ctx.beginPath(); canvas.toBuffer(function (err, buf) {
for (var iEdge=nEdges-1; iEdge>=0; iEdge-=1) { if (err) throw err
edge = edges[iEdge];
v = edge.va; var duration = new Date() - start
ctx.moveTo(v.x,v.y); console.log('Rendered in %dms', duration)
v = edge.vb;
ctx.lineTo(v.x,v.y); res.writeHead(200, {
} 'Content-Type': 'image/png',
ctx.stroke(); 'Content-Length': buf.length
} })
canvas.toBuffer(function(err, buf){ res.end(buf)
var duration = new Date - start; })
console.log('Rendered in %dms', duration); }).listen(3000, function () {
res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': buf.length }); console.log('Server running on port 3000')
res.end(buf); })
});
}).listen(3000);
console.log('Server running on port 3000');

5
package.json

@ -24,7 +24,7 @@
"prebenchmark": "node-gyp build", "prebenchmark": "node-gyp build",
"benchmark": "node benchmarks/run.js", "benchmark": "node benchmarks/run.js",
"pretest": "node-gyp build", "pretest": "node-gyp build",
"test": "mocha test/*.test.js", "test": "standard examples/*.js && mocha test/*.test.js",
"pretest-server": "node-gyp build", "pretest-server": "node-gyp build",
"test-server": "node test/server.js" "test-server": "node test/server.js"
}, },
@ -35,7 +35,8 @@
"body-parser": "^1.13.3", "body-parser": "^1.13.3",
"express": "^4.13.2", "express": "^4.13.2",
"jade": "^1.11.0", "jade": "^1.11.0",
"mocha": "*" "mocha": "*",
"standard": "^7.1.1"
}, },
"engines": { "engines": {
"node": ">=0.8.0" "node": ">=0.8.0"

Loading…
Cancel
Save