Javascript 如何使拖放到画布的图像对其他客户端可见?
我正在制作一个协作白板。到目前为止,您可以绘制并打开多个localhost选项卡,当我在画布中绘制一个选项卡时,您也可以在另一个选项卡中看到该绘图。现在我还想通过拖放图像来实现这一点。我该怎么做? 以下是完整的代码:Javascript 如何使拖放到画布的图像对其他客户端可见?,javascript,jquery,node.js,reactjs,Javascript,Jquery,Node.js,Reactjs,我正在制作一个协作白板。到目前为止,您可以绘制并打开多个localhost选项卡,当我在画布中绘制一个选项卡时,您也可以在另一个选项卡中看到该绘图。现在我还想通过拖放图像来实现这一点。我该怎么做? 以下是完整的代码: import io from 'socket.io-client'; import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import DragMove from "../D
import io from 'socket.io-client';
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import DragMove from "../DragMove";
import $ from 'jquery';
import Safe from "react-safe";
import 'jquery-ui-dist/jquery-ui';
import Draggable from 'react-draggable';
import useImage from 'use-image';
import './style.css';
class Board extends React.Component {
timeout;
socket = io.connect("http://localhost:5000");
ctx;
isDrawing = false;
constructor(props) {
super(props);
this.state ={
userData:[],
newData:[],
searchedValue: '',
loaded:false
}
this.socket.on("canvas-data", function(data){
var root = this;
var interval = setInterval(function(){
if(root.isDrawing) return;
root.isDrawing = true;
clearInterval(interval);
var image = new Image();
var canvas = document.querySelector('#board');
var ctx = canvas.getContext('2d');
image.onload = function() {
ctx.drawImage(image, 0, 0);
root.isDrawing = false;
};
image.src = data;
}, 200)
})
}
handlePress = async () => {
console.log("function is called");
fetch('http://localhost:5000/testData?title_picture=' + this.state.searchedValue, {
"method": "GET"
})
.then((response) => response.json())
.then((responseData) => {
this.setState({newData: responseData,
loaded:true})
}, () => {
console.log(this.state.newData);
})
}
async componentDidMount() {
this.drawOnCanvas();
const url = "http://localhost:5000/user";
const response = await fetch(url);
const data = await response.json();
this.setState({newData: data});
$(function(){
var img = document.querySelector("Drop");
//Make every clone image unique.
var counts = [0];
var resizeOpts = {
handles: "all" ,autoHide:true
};
$(".dragImg").draggable({
helper: "clone",
//Create counter
start: function() { counts[0]++; }
});
$("#dropHere").droppable({
drop: function(e, ui){
if(ui.draggable.hasClass("dragImg")) {
$(this).append($(ui.helper).clone());
//Pointing to the dragImg class in dropHere and add new class.
$("#dropHere .dragImg").addClass("item-"+counts[0]);
$("#dropHere .img").addClass("imgSize-"+counts[0]);
//Remove the current class (ui-draggable and dragImg)
$("#dropHere .item-"+counts[0]).removeClass("dragImg ui-draggable ui-draggable-dragging");
$(".item-"+counts[0]).dblclick(function() {
$(this).remove();
});
make_draggable($(".item-"+counts[0]));
$(".imgSize-"+counts[0]).resizable(resizeOpts);
}
}
});
var zIndex = 0;
function make_draggable(elements)
{
elements.draggable({
containment:'parent',
start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
stop:function(e,ui){
}
});
}
});
}
componentWillReceiveProps(newProps) {
this.ctx.strokeStyle = newProps.color;
this.ctx.lineWidth = newProps.size;
}
drawOnCanvas() {
var canvas = document.querySelector('#board');
console.log("canvas" + canvas);
this.ctx = canvas.getContext('2d');
var ctx = this.ctx;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = this.props.size;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = this.props.color;
canvas.addEventListener('mousedown', function(e) {
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var root = this;
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
if(root.timeout != undefined) clearTimeout(root.timeout);
root.timeout = setTimeout(function(){
var base64ImageData = canvas.toDataURL("image/png");
console.log(base64ImageData);
root.socket.emit("canvas-data", base64ImageData);
}, 1000)
};
}
render() {
const {searchedValue} = this.state;
console.warn(this.state);
return (
<div className="sketch" id="sketch">
<h4>Select picture!</h4>
<input type="text" value={this.state.searchedValue} onChange={(e)=>{this.setState({searchedValue: e.target.value})}}/>
<button onClick={() => this.handlePress()}>Search</button>
{this.state.newData.map((data) => (
<div class="dragImg">
<img src={data.picture} class="img"/>
</div>
))}
<div className="Drop" id="dropHere">
<canvas className="board" id="board"></canvas>
</div>
</div>
)
}
}
export default Board
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const mysql = require('mysql')
var bodyParser = require('body-parser');
app.use(bodyParser.json({type:'application/json'}));
app.use(bodyParser.urlencoded({extended:true}));
const connection = mysql.createConnection({
host: "localhost",
port: "3306",
user: "root",
password: "xxxxxxx",
database: "pictures"
})
connection.connect(function(error){
if(error) console.log(error);
else console.log("connected");
});
app.get('/user', function(req, res){
res.header('Access-Control-Allow-Origin', '*');
connection.query('select * from pictures', function(error, rows, fields){
if(error) console.log(error);
else{
console.log(rows);
res.send(rows);
}
});
});
app.get('/testData', function (req, res) {
res.header('Access-Control-Allow-Origin', '*');
connection.query("select * from pictures WHERE title_picture=?", req.query.title_picture, function(error, results, fields) {
if(error) {
console.log('Error in GET / query')
} else {
res.send(results);
}
})
})
io.on('connection', (socket)=> {
console.log('User Online');
socket.on('canvas-data', (data)=> {
socket.broadcast.emit('canvas-data', data);
console.log("receiving" + data);
socket.broadcast.emit('board-data', data);
})
})
var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
http.listen(server_port, () => {
console.log("Started on : "+ server_port);
})