Example
Co-op paiter
Code
<template>
<div>
<div id="draw">
<div id="container">
<canvas id="canvas" width="350" height="250"
@mousedown="drawing = true"
@mouseup="drawing = prev = false"
@mousemove="mouseMove"
></canvas>
</div>
<div id='buttons'>
color:
<select v-model="color">
<option v-for="_color in colors">{{ _color }}</option>
</select>
width:
<select v-model="width">
<option v-for="_width in brushes">{{ _width }}</option>
</select>
</div>
</div>
</div>
</template>
<script>
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
export default {
name: 'painter',
data() {
return {
canvas: null,
drawing: false,
prev: false,
color: 'red',
width: 1,
colors: [
'red',
'blue',
'green',
'black',
'yellow',
'cyan',
'magenta'
],
brushes: [
1,
2,
3,
5,
8
]
}
},
mounted() {
this.canvas = document.getElementById('canvas');
},
created() {
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'websocketkey',
cluster: 'mt1',
forceTLS: false,
wsHost: window.location.hostname,
wsPort: 80,
disableStats: true,
});
window.Echo.join('room.public')
.listenForWhisper('draw', (e) => {
this.draw(e.from, e.to, e.color, e.width);
})
.error((error) => {
console.error(error);
});
},
methods: {
draw(from, to, color, width) {
var context = this.canvas.getContext('2d');
context.strokeStyle = color;
context.lineWidth = width;
context.beginPath();
context.moveTo(from.x, from.y);
context.lineTo(to.x, to.y);
context.stroke();
},
mouseMove(e) {
var context = this.canvas.getContext('2d');
if (this.drawing) {
if (this.prev !== false) {
this.draw(
{x: this.prev.x, y: this.prev.y},
{x: e.offsetX, y: e.offsetY},
this.color,
this.width
);
window.Echo.join('room.public')
.whisper('draw', {
from: {x: this.prev.x, y: this.prev.y},
to: {x: e.offsetX, y: e.offsetY},
color: this.color,
width: this.width
});
}
this.prev = {x: e.offsetX, y: e.offsetY};
}
}
}
}
</script>