问题
Below is a basic growing effect in Konvas.js (v 2.4), starting from the upper left corner of the image (https://codepen.io/simedia/pen/mzrvJq)
var width = window.innerWidth;
var height = window.innerHeight;
// where everything stands in Konvas
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
// image object in Konvas
var kim = new Konva.Image({
x: 10,
y: 10,
scaleX: 0,
scaleY: 0,
});
layer.add(kim);
stage.add(layer);
// tween for growing effect
var tween = new Konva.Tween({
node: kim,
duration: 4,
scaleX: 1,
scaleY: 1,
});
// DOM image
var img = new Image();
img.onload = function() {
kim.image(this); // link to Konvas
tween.play(); // start tween
};
// the result appears when image is loaded !
img.src="https://dummyimage.com/200x200/224488/fff.png&text=Salut+le+monde";
My question is how to make it grow from the center of the image ? Thanks
回答1:
Your code works fine, you just need to move the shape further into the layer so when it grows it does not clip, and move the offset point which is what Konvajs uses as the origin for scaling. I simply added these lines to the onload() event for the image. Working snippet below.
kim.x(kim.width()/2); // move shape top-left so it can grow and not get cut off
kim.y(kim.height()/2);
kim.offsetX(kim.width()/2); // Move the offset to the centre of the shape
kim.offsetY(kim.height()/2);
var width = window.innerWidth;
var height = window.innerHeight;
// where everything stands in Konvas
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
// image object in Konvas
var kim = new Konva.Image({
x: 10,
y: 10,
scaleX: 0,
scaleY: 0,
});
layer.add(kim);
stage.add(layer);
// tween for growing effect
var tween = new Konva.Tween({
node: kim,
duration: 4,
scaleX: 1,
scaleY: 1,
});
// DOM image
var img = new Image();
img.onload = function() {
kim.image(this); // link to Konvas
kim.x(kim.width()/2); // move the image top-left into the layer so it can grow and not get cut off
kim.y(kim.height()/2);
kim.offsetX(kim.width()/2); // Move the offset to the centre of the shape
kim.offsetY(kim.height()/2);
tween.play(); // start tween
};
// the result appears when image is loaded !
img.src="https://dummyimage.com/200x200/224488/fff.png&text=Salut+le+monde";
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<div id="container"></div>
来源:https://stackoverflow.com/questions/52685855/konvajs-how-to-apply-scale-effect-from-the-center-to-an-image