canvas画图小例子

<!DOCTYPE html>
<html lang="en">
<head>
<title>画图</title>
<meta charset="utf-8">
</head>
<body>
<div id="con" style="width:500px;height:450px;border:1px solid red;text-align: center;">
<canvas id="can" width="500" height="400" style="border:1px solid black;background-color: white;">
你的浏览器不支持canvas!
</canvas>
<p>
<input id="start" type="button" value="开始绘图">
线宽:<select id="sel" value="1">
<option>1</option>
<option>2</option>
<option>4</option>
<option>6</option>
</select>
颜色<input id="col" type="color" />
<input id="clear" type="button" value="清除">
<input id="eraser" type="button" value="橡皮擦">
</p>
</div>
</body>
</body>
<script>
var ca=document.getElementById("can");
var ctx=ca.getContext("2d");
var bodyWidth=document.body.clientWidth;
var px;var py;
var f=false;
ca.οnmοusedοwn=function(e){
px=e.clientX;
py=e.clientY;
f=true;
if(!ef){
ca.style.cursor="default";
}
else{
ca.style.cursor="pointer";
}
}
var lx=0;
var ly=0;
var w=10;
ca.οnmοusemοve=function(e){
if(f){
var x=e.clientX;
var y=e.clientY;
ctx.beginPath();
ctx.lineWidth=value;
ctx.strokeStyle=color;
ctx.moveTo(px,py);
ctx.lineTo(x,y);
ctx.stroke();
px=x;py=y;
}
if(ef){
ctx.clearRect(lx-w-2,ly-w-2,2*w+5,2*w+5);
lx=e.clientX;
ly=e.clientY;
ctx.lineWidth=1;
ctx.strokeStyle="#000";
ctx.beginPath();
ctx.rect(lx-w,ly-w,2*w,2*w);
ctx.stroke();
}
}
ca.οnmοuseup=function(e){
f=false;
}
//ca.οnmοuseοut=function(e){
//f=false;
//}
var se=document.getElementById("sel");//Ïß¿í
var value=se.value;
var co=document.getElementById("col");//ÑÕÉ«
var color=co.value;
se.οnchange=function(){
value=this.value;
}
co.οnchange=function(){
color=this.value;
}
var cl=document.getElementById('clear');//Çå¿Õ
cl.οnclick=function(){
ctx.clearRect(0,0,ca.width,ca.height);
}
var er=document.getElementById('eraser');//ÏðƤ²Á
var ef=false;
er.οnclick=function(){
ef=true;
f=false;
ca.style.cursor="pointer";
}
var st=document.getElementById('start');//Çå¿Õ
st.οnclick=function(){
ctx.clearRect(lx-w-2,ly-w-2,2*w+5,2*w+5);
ef=false;
ca.style.cursor="default";
}
document.οnkeydοwn=function keyDown(e){
if(e.keyCode==221){//]
if(w<25){
w+=2;
}
ctx.clearRect(lx-w-2,ly-w-2,2*w+5,2*w+5);
ctx.beginPath();
ctx.lineWidth=1;
ctx.strokeStyle="#000";
ctx.rect(lx-w,ly-w,2*w,2*w);
ctx.stroke();

else if(e.keyCode==219){//[
ctx.clearRect(lx-w-2,ly-w-2,2*w+5,2*w+5);
if(w>5){
w-=2;
}
ctx.beginPath();
ctx.lineWidth=1;
ctx.strokeStyle="#000";
ctx.rect(lx-w,ly-w,2*w,2*w);
ctx.stroke();
}
}
</script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值