点点连线:
<style>*{padding: 0
margin: 0}
#can{border:1px solid #ccc}
</style>
<body>
<canvas id="can" width="600" height="600"></canvas>
</body>
<script>
var _canvas=document.getElementById("can")
var obj=_canvas.getContext("2d")
var arr=[]
_canvas.onclick = function(e){
obj.beginPath()
obj.moveTo(arr[0],arr[1])
obj.lineTo(e.offsetX,e.offsetY)
obj.stroke()
arr=[]
arr.unshift(e.offsetX)
arr.push(e.offsetY)
}
</script>
模仿画笔:
<style type="text/css">#_canvas{
background-color: rgb(240,240,240)
}
</style>
</head>
<body>
<canvas id="_canvas">sorry, your broswer does not support html5!</canvas>
<script type="text/javascript">
var canvas_ = document.getElementById("_canvas")
//全屏
canvas_.setAttribute("width",screen.width)
canvas_.setAttribute("height",screen.height)
var context = canvas_.getContext("2d")
context.strokeStyle = "blue"
context.lineWidth = 4
var array_paint = []
var current_y = 0
var current_x = 0
//判断鼠标是否按下
var m_down = false
function paint()
{
context.beginPath()
context.moveTo(array_paint[0][0],array_paint[0][1])
if(array_paint.length == 1)
context.lineTo(array_paint[0][0] +1,array_paint[0][1] +1)
else
{
var i =1
for(i in array_paint)
{
context.lineTo(array_paint[i][0],array_paint[i][1])
context.moveTo(array_paint[i][0],array_paint[i][1])
}
}
context.closePath()
context.stroke()
}
//按下鼠标
canvas_.onmousedown = function(event)
{
m_down = true
current_x = event.offsetX
current_y = event.offsetY
array_paint.push([current_x,current_y])
paint()
}
//鼠标松开,清空数据
canvas_.onmouseup = function(event)
{
m_down = false
array_paint = []
}
//鼠标按下后拖动
canvas_.onmousemove = function(event)
{
if(m_down)
{
current_x = event.offsetX
current_y = event.offsetY
array_paint.push([current_x,current_y])
paint()
}
}
</script>
</body>
需要准备的材料分别有:电脑、chrome浏览器、html编辑器。
1、首先打开html编辑器,新建一个html文件,例如:index.html。
2、其次,在index.html的<body>标签中,添加代码:<hr/>。
3、浏览器运行index.html页面,此时成功在html中画了一条线。