Skip to main content

How to apply canvas filters with Vue and Konva?

To apply filters you need to cache Konva.Node manually. You can do it in the mounted() hook. You will need to recache nodes every time you update their styles.

Instructions: Move your mouse over the rectangle to see color changes with noise filter applied.

<template>
  <v-stage ref="stage" :config="stageSize">
    <v-layer ref="layer">
      <v-rect
        ref="rect"
        @mousemove="handleMouseMove"
        :config="{
          filters: filters,
          noise: 1,
          x: 10,
          y: 10,
          width: 50,
          height: 50,
          fill: color,
          shadowBlur: 10
        }"
      />
    </v-layer>
  </v-stage>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;
import Konva from 'konva';

export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height
      },
      color: 'green',
      filters: [Konva.Filters.Noise]
    };
  },
  methods: {
    handleMouseMove() {
      this.color = Konva.Util.getRandomColor();
      // recache after changing properties
      const rectNode = this.$refs.rect.getNode();
      rectNode.cache();
    }
  },
  mounted() {
    // initial cache
    const rectNode = this.$refs.rect.getNode();
    rectNode.cache();
  }
};
</script>