slitscan/src/components/Canvas.vue

99 lines
2.3 KiB
Vue
Raw Normal View History

2018-01-17 17:59:50 +01:00
<template>
<div id="canvas-container">
<canvas ref="canvas" id="canvas"></canvas>
2018-01-17 17:59:50 +01:00
</div>
</template>
<script>
2019-10-31 15:51:31 +01:00
import {getDimsFit} from "../helpers/image.js";
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
export default {
name: "Canvas",
data: function () {
return {
imageUrl: "",
image: null,
imageLoaded: false,
slice: [0, 0],
};
},
computed: {},
watch: {
imageUrl: function (url) {
this.loadImage(url);
2018-01-17 17:59:50 +01:00
},
2019-10-31 15:51:31 +01:00
slice: function () {
this.refresh();
2018-01-17 17:59:50 +01:00
},
2019-10-31 15:51:31 +01:00
},
mounted: function () {
window.addEventListener("resize", this.handleResize);
this.handleResize();
},
methods: {
loadImage: function (imageUrl) {
this.image = new Image();
this.image.onload = () => {
this.imageLoaded = true;
this.$bus.$emit("imageLoaded", this.image);
this.refresh();
};
this.image.src = imageUrl;
2018-01-17 17:59:50 +01:00
},
2019-10-31 15:51:31 +01:00
refresh: function () {
if (!this.imageLoaded) return;
let image = this.image;
let canvas = this.$refs.canvas;
let ctx = canvas.getContext("2d");
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
ctx.clearRect(0, 0, canvas.width, canvas.height);
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
let dims = getDimsFit(image.width, image.height, canvas.width, canvas.height);
ctx.drawImage(image,
0, 0, image.width, image.height,
0, 0, dims.width, dims.height);
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
let ratio = dims.width / image.width;
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
let sliceX = parseInt(this.slice[0]) * ratio;
let sliceY = parseInt(this.slice[1]) * ratio;
2018-01-17 17:59:50 +01:00
2019-10-31 15:51:31 +01:00
if (sliceX > 0 && sliceY > 0) {
for (let x = 0; x < dims.width; x += sliceX) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, dims.height);
ctx.strokeStyle = "red";
ctx.stroke();
}
for (let y = 0; y < dims.height; y += sliceY) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(dims.width, y);
ctx.strokeStyle = "red";
ctx.stroke();
2018-01-17 17:59:50 +01:00
}
}
2019-10-31 15:51:31 +01:00
},
handleResize: function () {
let canvasContainer = document.getElementById("canvas-container");
let canvas = document.getElementById("canvas");
canvas.width = canvasContainer.offsetWidth - 10;
canvas.height = canvasContainer.offsetHeight - 10;
this.refresh();
},
},
};
2018-01-17 17:59:50 +01:00
</script>
<style scoped>
2019-10-31 15:51:31 +01:00
#canvas-container {
width: 100%;
height: 100%;
margin: 0;
border: 0;
padding: 0;
}
2018-01-17 17:59:50 +01:00
</style>