Konvajs如何将缩放效果从中心应用到图像

时间:2018-10-07 05:56:42

标签: javascript html5-canvas effects konvajs

以下是Konvas.js(v 2.4)中的基本生长效果,从图像的左上角(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";

我的问题是如何使其从图像的中心生长?谢谢

1 个答案:

答案 0 :(得分:2)

您的代码可以正常工作,您只需要将形状进一步移动到图层中,这样在形状增长时就不会剪切,并移动偏移点,这是Konvajs用作缩放原点的地方。我只是将这些行添加到图像的onload()事件。下面的工作片段。

  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>