konva/konva-node/demo.js

78 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2021-05-09 21:11:42 +08:00
import fs from 'fs';
2017-10-11 16:17:54 +08:00
// relative path here
// but you will need just require('konva-node');
2021-05-09 21:11:42 +08:00
import Konva from '../';
2014-03-04 19:40:06 +08:00
// Create stage. Container parameter is not required in NodeJS.
2015-01-27 15:07:51 +08:00
var stage = new Konva.Stage({
2017-07-31 17:34:10 +08:00
width: 100,
2020-11-10 21:59:20 +08:00
height: 100,
2014-02-27 19:55:39 +08:00
});
2015-01-27 15:07:51 +08:00
var layer = new Konva.Layer();
stage.add(layer);
2020-11-10 21:59:20 +08:00
2015-01-27 15:07:51 +08:00
var rect = new Konva.Rect({
2017-07-31 17:34:10 +08:00
width: 100,
height: 100,
x: 50,
y: 50,
2020-11-10 21:59:20 +08:00
fill: 'white',
2014-02-27 19:55:39 +08:00
});
2015-01-27 15:07:51 +08:00
var text = new Konva.Text({
2017-07-31 17:34:10 +08:00
text: 'Generated inside node js',
x: 20,
y: 20,
2020-11-10 21:59:20 +08:00
fill: 'black',
2014-02-27 19:55:39 +08:00
});
layer.add(rect).add(text);
layer.draw();
stage.setSize({
2017-07-31 17:34:10 +08:00
width: 200,
2020-11-10 21:59:20 +08:00
height: 200,
});
// check tween works
2015-01-27 15:07:51 +08:00
var tween = new Konva.Tween({
2017-07-31 17:34:10 +08:00
node: rect,
duration: 1,
2020-11-10 21:59:20 +08:00
x: -50,
});
tween.play();
2014-03-04 19:40:06 +08:00
// After tween we want to convert stage to dataURL
2020-11-10 21:59:20 +08:00
setTimeout(function () {
2017-07-31 17:34:10 +08:00
stage.toDataURL({
2020-11-10 21:59:20 +08:00
callback: function (data) {
2017-07-31 17:34:10 +08:00
// Then add result to stage
var img = new Konva.window.Image();
2020-11-10 21:59:20 +08:00
img.onload = function () {
2017-07-31 17:34:10 +08:00
var image = new Konva.Image({
image: img,
x: 10,
2020-11-10 21:59:20 +08:00
y: 50,
2017-07-31 17:34:10 +08:00
});
layer.add(image);
layer.draw();
// save stage image as file
stage.toDataURL({
2020-11-10 21:59:20 +08:00
callback: function (data) {
2017-07-31 17:34:10 +08:00
var base64Data = data.replace(/^data:image\/png;base64,/, '');
2020-11-10 21:59:20 +08:00
fs.writeFile('./out.png', base64Data, 'base64', function (err) {
2017-07-31 17:34:10 +08:00
err && console.log(err);
console.log('See out.png');
});
2019-07-11 05:59:39 +08:00
// now try to create image from url
Konva.Image.fromURL(data, () => {
2019-07-18 08:55:22 +08:00
console.log('image loaded');
2019-07-11 05:59:39 +08:00
// shoul'd throw
});
2020-11-10 21:59:20 +08:00
},
2017-07-31 17:34:10 +08:00
});
};
img.src = data;
2020-11-10 21:59:20 +08:00
},
2017-07-31 17:34:10 +08:00
});
}, 1050);