在线黑板
前置准备
先用canvas做一个简易版的黑板,能改变笔触的颜色和粗细,并将当前绘图复制到另一个元素上
这个简易版黑板的代码也可以看一下
<style>
.can{
border: 2px black solid;
top:100px;
margin:auto;
}
#show{
border: 2px black solid;
top:100px;
height:500px;
width:500px;
left:0px;
}
</style>
<script>
var color='black';
var width=5;
var x1,y1,x2,y2;
var isMouseDown=false;
var canvas;
var context;
var container;
window.onload=function(){
canvas=document.getElementById('canvas');
context=canvas.getContext("2d");
container=document.getElementById('container');
container.onmousedown=mouseDownAction;
document.onmouseup=mouseUpAction;
canvas.onmousemove=mouseMoveAction;
console.log(canvas,context);
}
function mouseDownAction(e){
isMouseDown=true;
// console.log(e);
x1=e.offsetX;
y1=e.offsetY;
console.log(x1,y1);
}
function mouseUpAction(){
isMouseDown=false;
}
function mouseMoveAction(e){
if (isMouseDown){
x2=e.offsetX;
y2=e.offsetY;
drawLine(x1,y1,x2,y2);
x1=x2;
y1=y2;
}
}
function drawLine(x1,y1,x2,y2){
context.beginPath();
context.moveTo(x1,y1);
context.lineWidth=width;
context.strokeStyle=color;
context.lineTo(x2,y2);
console.log(color,width);
context.stroke();
}
function showRange(){
console.log(document.getElementById('width').value);
width=document.getElementById('width').value/10;
}
function showColor(){
console.log(document.getElementById('color').value);
color=document.getElementById('color').value;
}
function broadcast(){
console.log(canvas.toDataURL("image/png",0.92));
var show=document.getElementById('show');
show.innerHTML="<img src='"+canvas.toDataURL("image/png",0.92)+"'>'"
}
function clearCan(){
context.clearRect(0,0,1000,1000);
}
</script>
<body>
<div class='center' id="container">
<canvas class