Skip to main content

如何用 Vue 绘制自定义画布形状?

要使用 vue-konva 创建自定义形状,我们应该使用 v-shape 组件。

在创建自定义形状时,我们需要定义一个绘图函数,该函数传递一个 Konva.Canvas 渲染器。 我们可以使用该渲染器访问 HTML5 Canvas 上下文,并使用特殊方法,如 context.fillStrokeShape(shape),该方法自动处理填充、边框和阴影的应用。

说明:演示展示了使用画布绘图命令绘制的自定义形状。

<template>
  <v-stage ref="stage" :config="stageSize">
    <v-layer>
      <v-shape :config="{
        width: 260,
        height: 170,
        sceneFunc: function(context, shape) {
          const width = shape.width();
          const height = shape.height();
          context.beginPath();
          context.moveTo(0, 0);
          context.lineTo(width - 40, height - 90);
          context.quadraticCurveTo(width - 110, height - 70, width, height);
          context.closePath();

          // (!) Konva 特有的方法,这非常重要
          context.fillStrokeShape(shape);
        },
        fill: '#00D2FF',
        stroke: 'black',
        strokeWidth: 4
      }"/>
    </v-layer>
  </v-stage>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;

export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height
      }
    };
  }
};
</script>