Below is a Vue app I wrote to draw a Sierpinski Triangle given n iterations, which can be incremented/decremented via a HTML input control. I was wondering if there were any ways this code could be optimized.
const app = new Vue({
el: "#app",
data: {
canvas: null,
context: null,
v1: 0,
v2: 0,
v3: 0,
n: 0
},
mounted: function () {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.v1 = { x: 0, y: this.canvas.height };
this.v2 = { x: this.canvas.width / 2, y: 0 };
this.v3 = { x: this.canvas.width, y: this.canvas.height };
},
watch: {
n: function (newValue) {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawSierpinskiTriangle(newValue, this.v1, this.v2, this.v3);
}
},
methods: {
drawSierpinskiTriangle: function (n, v1, v2, v3) {
if (n <= 0) {
return;
}
this.drawTriangle(v1, v2, v3);
let m1 = {
x: (v1.x + v2.x) / 2,
y: (v2.y + v1.y) / 2
};
let m2 = {
x: (v2.x + v3.x) / 2,
y: (v2.y + v3.y) / 2
};
let m3 = {
x: (v1.x + v3.x) / 2,
y: (v1.y + v3.y) / 2
};
this.drawSierpinskiTriangle(n - 1, v1, m1, m3);
this.drawSierpinskiTriangle(n - 1, m1, v2, m2);
this.drawSierpinskiTriangle(n - 1, m3, m2, v3);
},
drawTriangle: function (v1, v2, v3) {
this.context.beginPath();
this.context.moveTo(v1.x, v1.y);
this.context.lineTo(v2.x, v2.y);
this.context.lineTo(v3.x, v3.y);
this.context.lineTo(v1.x, v1.y);
this.context.stroke();
}
}
});
body * {
margin: 5px;
border-radius: 5px;
}
input {
display: block;
font-size: 16px;
font-weight: bold;
}
canvas {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
<input type='number' v-model='n' min='0' max='10' />
<canvas id='canvas' height='400' width='500'></canvas>
</div>