Share This Post

什麼是Konva

Konva 是一個 JavaScript 的程式庫,它提供了一個簡單的API,使得開發人員可以使用JavaScript創建圖形、文字和圖像等元素,並且可以對這些元素進行編輯、縮放、旋轉、拖動等操作。它還支持圖層、事件處理和動畫等功能。

Get start

本篇透過vue進行實作。

npm install vue-konva konva --save
import { createApp } from 'vue';
import App from './App.vue';
import VueKonva from 'vue-konva';

const app = createApp(App);
app.use(VueKonva);
app.mount('#app');

簡單的範例

App.vue

<template>
  <div>
    <v-stage ref="stage" :config="stageSize">
      <v-layer>
      <v-text :config="{text: 'Some text on canvas', fontSize: 15}"/>
      <v-rect :config="{
          x: 20,
          y: 50,
          width: 100,
          height: 100,
          fill: 'red',
          shadowBlur: 10
        }"
      />
      <v-circle :config="{
          x: 200,
          y: 100,
          radius: 50,
          fill: 'green'
        }"
      />
      <v-line :config="{
        x: 20,
        y: 200,
        points: [0, 0, 100, 0, 100, 100],
        tension: 0.5,
        closed: true,
        stroke: 'black',
        fillLinearGradientStartPoint: { x: -50, y: -50 },
        fillLinearGradientEndPoint: { x: 50, y: 50 },
        fillLinearGradientColorStops: [0, 'red', 1, 'yellow']
      }"/>
      </v-layer>
      <v-layer ref="dragLayer"></v-layer>
    </v-stage>
  </div>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;
let vm = {};
export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height
      }
    };
  }
};
</script>

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>CodeSandbox vue-konva demo</title>
</head>

<body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
</body>

</html>

結果會長這樣:

在konva中有提供 v-rect,v-circle, v-ellipse, v-line, v-image, v-text, v-text-path, v-star,v-label, v-path, v-regular-polygon 這些形狀可做選擇。

如果要欻一個不規則的形狀的話,可以透過v-shape
像是這樣:

        <v-shape :config="{
        sceneFunc: function(context, shape) {
          context.beginPath();
          context.moveTo(20, 50);
          context.lineTo(220, 80);
          context.quadraticCurveTo(150, 100, 260, 170);
          context.closePath();

          // special Konva.js method
          context.fillStrokeShape(shape);
        },
        fill: '#00D2FF',
        stroke: 'black',
        strokeWidth: 4
      }"/>

訂閱研究文章

Get updates and learn from the best