html5新特性初探之canvas绘图
概述
按照书上的代码手工敲的,另外由于书出版比较早,有些地方的写法已经过时了,做了一些修改。比如var 改为了let,div上面的属性 align="center" 已经废弃了,就直接删除了。
效果操作演示
教程源码
完整demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas绘图</title>
<style>
body,div,ul,li{
margin:0;
padding:0;
text-align:center;
}
ul,li{
list-style:none
}
#cav{
border:2px solid #000;
border-radius:4px;
box-shadow:0 0 10px #000;
}
#bk{
margin:10px auto;
width: 400px;
height:36px;
}
.bk{
text-align:center;
width:20px;
height:10px;
margin:12px;
display:inline-block;
border:1px dotted gray;
}
.tips{
margin-top: 20px;
}
</style>
</head>
<body>
<div id="bk"></div>
<canvas id="cav" width="400" height="300"></canvas>
<div class="tips">
<ul>
<li>操作说明:</li>
<li>点击上面笔触颜色,可以切换绘制颜色</li>
</ul>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
let bColor=[
"#000",
"#999",
"#c6f",
"#f00",
"#f90",
"#ff0",
"#008000",
"#0cf",
]
let col="#f00"
function initBrush(){
for(let i=0;i<bColor.length;i++){
let bk=$("<span class='bk'></span>")
.css("background-color",bColor[i])
.click(function(){
col=$(this).css("background-color")
})
$("#bk").append(bk)
}
}
function initPainter(){
let can=$("#cav"),self=this,x=0,y=0;
let ctx=can[0].getContext("2d")
ctx.lineWidth=2
can.on("mousedown",function(e){
e.preventDefault()
ctx.strokeStyle=col;
x=e.offsetX;
y=e.offsetY;
ctx.beginPath()
ctx.moveTo(x,y)
can.on("mousemove",function(e){
let nx=event.offsetX,
ny=event.offsetY
ctx.lineTo(x,y)
ctx.stroke()
x=nx
y=ny
})
can.on("mouseup",function(){
can.off("mousemove")
})
})
}
$(function(){
initBrush()
initPainter()
})
</script>
</html>
|