Load HTML5 Canvas Stage from JSON Tutorial

获取Konva最新的信息

How to import canvas from JSON?

To load a complex stage that originally contained images and event bindings using Konva,
we need to create a stage node using Konva.Node.create(), and then set the
images and event handlers with the help of selectors using the find() method.
Images and event handlers must be manually set because they aren’t serializable.

That methods works for small apps. For more complex cases take a look into Best Practices

Konva Load Complex Stage Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Load Complex Stage Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var json =
'{"attrs":{"width":578,"height":200},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"width":"auto","height":"auto","text":"Text Shadow!","fontFamily":"Calibri","fontSize":95,"x":20,"y":20,"stroke":"red","strokeWidth":2,"shadowColor":"black","shadowBlur":2,"shadowOffsetX":10,"shadowOffsetY":10,"shadowOpacity":0.5},"className":"Text"},{"attrs":{"stroke":"green","strokeWidth":10,"lineJoin":"round","lineCap":"round","points":[{"x":50,"y":140},{"x":450,"y":160}],"shadowColor":"black","shadowBlur":10,"shadowOffsetX":5,"shadowOffsetY":5,"shadowOpacity":0.5},"className":"Line"},{"attrs":{"x":280,"y":100,"width":100,"height":50,"fill":"#00D2FF","stroke":"black","strokeWidth":4,"shadowColor":"black","shadowBlur":10,"shadowOffsetX":5,"shadowOffsetY":5,"shadowOpacity":0.5,"rotation":0.34.0.188503988659,"id":"blueRectangle"},"className":"Rect"},{"attrs":{"x":100,"y":41,"width":106,"height":118,"id":"yodaImage"},"className":"Image"}]}]}';

var stage = Konva.Node.create(json, 'container');

/*
* set functions
*/
stage.find('#blueRectangle').on('mouseover mouseout', function() {
var stroke = this.stroke();
this.stroke(stroke === 'black' ? 'red' : 'black');
stage.draw();
});
/*
* set images
*/
var imageObj = new Image();
imageObj.onload = function() {
stage.find('#yodaImage')[0].image(imageObj);
stage.draw();
};
imageObj.src = '/assets/yoda.jpg';
</script>
</body>
</html>