vue
<template>
<div id="app">
<canvas
ref="canvas"
:width="width"
:height="height"
@mousemove="brush"
style="border:1px solid #000;">
</canvas>
<button @click="generateImage">生成图片</button>
<br>
<img :src="generatedImage" alt="Generated Image">
</div>
</template>
<script>
export default {
data() {
return {
width: 800,
height: 600,
brushSize: 20,
ctx: null,
renderedImageData: null,
generatedImage: null
};
},
mounted() {
this.setupCanvas();
},
methods: {
setupCanvas() {
const canvas = this.$refs.canvas;
this.ctx = canvas.getContext('2d');
this.ctx.fillStyle = 'black';
this.ctx.fillRect(0, 0, this.width, this.height);
this.ctx.globalCompositeOperation = 'destination-out';
},
brush(evt) {
const rect = this.$refs.canvas.getBoundingClientRect();
const x = evt.clientX - rect.left;
const y = evt.clientY - rect.top;
this.ctx.beginPath();
this.ctx.arc(x, y, this.brushSize, 0, 2 * Math.PI);
this.ctx.fill();
},
generateImage() {
const imageData = this.ctx.getImageData(0, 0, this.width, this.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
let brightness = (data[i] + data[i + 1] + data[i + 2]) / 3;
let value = brightness > 125 ? 255 : 0; // Threshold
data[i] = data[i + 1] = data[i + 2] = value;
}
this.ctx.putImageData(imageData, 0, 0);
const url = this.$refs.canvas.toDataURL();
this.generatedImage = url;
}
}
};
</script>
<style>
#app {
text-align: center;
margin-top: 50px;
}
</style>