Search code examples
javascriptvue.jscamanjs

Reload canvas on change Vue.Js + HTML Range


I'm trying reload a image on when I change a value but my vue.js just execute one time my function. Basically I will use a Caman.js to apply a 'threshold' and 'sharpen' that a user change a range and show a sample.

HTML

<div id="app">
...
<canvas id="canvas" style="width: 1024px; border:2px solid #333;"></canvas>
...
<input id="sharpen_control" v-model="sharpen_mod" @change="reloadCanvas()" type="range" min="1" max="200">
                   
<input id="threshold_control" v-model="threshold_mod" @change="reloadCanvas()" type="range" min="1" max="200">
...
</div>

Vue.js

el: '#app',
    data: {
        sharpen_mod: '50',
        threshold_mod: '50'
    },
    mounted() {
       this.loadCanvas()
    },

    methods: {
        loadCanvas(){

            const self = this
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');

            const img = new Image();
            img.crossOrigin = 'anonymous';

            img.onload = function() {
                canvas.width = img.naturalWidth
                canvas.height = img.naturalHeight
                ctx.drawImage(img, 0, 0);
            }

            img.src = 'https://i.ibb.co/SNYCXcf/img.jpg';

        },
        reloadCanvas() {
            this.loadCanvas()
            this.drawCanvas()
        },
        drawCanvas(){
            const self = this
            Caman('#canvas', function() {
                this.sharpen(self.sharpen_mod).contrast(5).clip(30).threshold(self.threshold_mod).render();
            });
        }
    }

Solution

  • Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

    With change it's inconsistent:

    const logValue = e => {
      document.getElementById('display-value').innerHTML = e.target.value;
    }
    <input type="range" onchange="logValue(event)" />
    <div id="display-value" />

    Try using input instead:

    const logValue = e => {
      document.getElementById('display-value').innerHTML = e.target.value;
    }
    <input type="range" oninput="logValue(event)" />
    <div id="display-value" />