Javascript HTML5 Canvas实现的一个画板
本文实例为大家分享了HTML5Canvas实现的一个画板代码,供大家参考,具体内容如下
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>DEMO6:自定义画板</title>
</head>
<body>
<canvasid="canvas"width="600"height="300">
浏览器不支持canvas<!--如果不支持会显示这段文字-->
</canvas>
<br/>
<buttonstyle="width:80px;background-color:yellow;"onclick='linecolor="yellow";'>YELLOW</button>
<buttonstyle="width:80px;background-color:red;"onclick='linecolor="red";'>RED</button>
<buttonstyle="width:80px;background-color:blue;"onclick='linecolor="blue";'>BLUE</button>
<buttonstyle="width:80px;background-color:green;"onclick='linecolor="green";'>GREEN</button>
<buttonstyle="width:80px;background-color:white;"onclick='linecolor="white";'>WHITE</button>
<buttonstyle="width:80px;background-color:black;"onclick='linecolor="black";'>BLACK</button>
<br/>
<buttonstyle="width:80px;background-color:white;"onclick="linw=4;">4PX</button>
<buttonstyle="width:80px;background-color:white;"onclick="linw=8;">8PX</button>
<buttonstyle="width:80px;background-color:white;"onclick="linw=16;">16PX</button>
<br/>
<buttonstyle="width:80px;background-color:white;"onclick="copyimage();">EXPORT</button>
<br/>
<imgsrc=""id="image_png"width="600px"height="300px">
<br/>
<scripttype="text/javascript">
varcanvas=document.getElementById('canvas');//获取标签
varctx=canvas.getContext("2d");
varfillStyle="black";
ctx.fillRect(0,0,600,300);
varonoff=false;//按下标记
varoldx=-10;
varoldy=-10;
//设置颜色
varlinecolor="white";
varlinw=4;
canvas.addEventListener("mousemove",draw,true);//鼠标移动事件
canvas.addEventListener("mousedown",down,false);//鼠标按下事件
canvas.addEventListener("mouseup",up,false);//鼠标弹起事件
functiondown(event){
onoff=true;
oldx=event.pageX-10;
oldy=event.pageY-10;
}
functionup(){
onoff=false;
}
functiondraw(event){
if(onoff==true){
varnewx=event.pageX-10;
varnewy=event.pageY-10
ctx.beginPath();
ctx.moveTo(oldx,oldy);
ctx.lineTo(newx,newy);
ctx.strokeStyle=linecolor;
ctx.lineWidth=linw;
ctx.lineCap="round";
ctx.stroke();
oldx=newx;
oldy=newy;
}
}
functioncopyimage(event)
{
varimg_png_src=canvas.toDataURL("image/png");//将画板保存为图片格式的函数
document.getElementById("image_png").src=img_png_src;
}
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助。