99 lines
2.3 KiB
Vue
99 lines
2.3 KiB
Vue
<template>
|
|
<div id="canvas-container">
|
|
<canvas ref="canvas" id="canvas"></canvas>
|
|
</div>
|
|
</template>
|
|
|
|
<script>
|
|
import {getDimsFit} from "../helpers/image.js";
|
|
|
|
export default {
|
|
name: "Canvas",
|
|
data: function () {
|
|
return {
|
|
imageUrl: "",
|
|
image: null,
|
|
imageLoaded: false,
|
|
slice: [0, 0],
|
|
};
|
|
},
|
|
computed: {},
|
|
watch: {
|
|
imageUrl: function (url) {
|
|
this.loadImage(url);
|
|
},
|
|
slice: function () {
|
|
this.refresh();
|
|
},
|
|
},
|
|
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;
|
|
},
|
|
refresh: function () {
|
|
if (!this.imageLoaded) return;
|
|
let image = this.image;
|
|
let canvas = this.$refs.canvas;
|
|
let ctx = canvas.getContext("2d");
|
|
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
|
|
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);
|
|
|
|
let ratio = dims.width / image.width;
|
|
|
|
let sliceX = parseInt(this.slice[0]) * ratio;
|
|
let sliceY = parseInt(this.slice[1]) * ratio;
|
|
|
|
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();
|
|
}
|
|
}
|
|
},
|
|
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();
|
|
},
|
|
},
|
|
};
|
|
</script>
|
|
|
|
<style scoped>
|
|
#canvas-container {
|
|
width: 100%;
|
|
height: 100%;
|
|
margin: 0;
|
|
border: 0;
|
|
padding: 0;
|
|
}
|
|
</style>
|