How to draw a straight line using HTML5 canvas?
Canvas, one of the new elements of HTML5, defines image drawing using JavaScript. It only takes a few simple steps to draw pictures in canvas with js.
- Get the canvas tag
- Get 2d context
- Use the drawing api to draw on the context
Show results
1. Add canvas tag to Html page
Declare the canvas tag on the html page.
<section>
<h1>context.LineTo(x, y)</h1>
<canvas id="canvas" width="200" height="150"></canvas>
<canvas id="canvas2" width="200" height="150"></canvas>
<canvas id="canvas3" width="200" height="150"></canvas>
<canvas id="canvas4" width="200" height="150"></canvas>
<canvas id="canvas5" width="200" height="150"></canvas>
</section>
In order to make the canvas element display more intuitively, we add a border style
canvas {
border:1px dashed gray;
}
2. The page javascript gets the canvas, gets the context, and then linesTo on the context
// 声明一个方法根据id获取dom元素
function $$(id){
return document.getElementById(id)
}
// 页面加载完成开始执行方法
window.onload = function() {
// 画1条直线
var cnv = $$('canvas') // 获取canvas
var ctx = cnv.getContext('2d') // 获取canvas的 2d context 2d绘图上下文
// console.log(ctx)
ctx.moveTo(50, 100) // 移动到坐标点x轴50, y轴100
ctx.lineTo(150, 50) // 在坐标(150,50)和上一个坐标(50, 100)用直线连接起来
ctx.stroke() // 描边绘制,默认stroke样式为黑色
// 画2条直线
var cnv2 = $$('canvas2')
var ctx2 = cnv2.getContext('2d')
ctx2.moveTo(50, 50)
ctx2.lineTo(100, 50)
ctx2.moveTo(50, 100)
ctx2.lineTo(100, 100)
ctx2.stroke()
// 画2条直线改动moveTo为lineTo变成3条直线
var cnv3 = $$('canvas3')
var ctx3 = cnv3.getContext('2d')
ctx3.moveTo(50, 50)
ctx3.lineTo(100, 50)
ctx3.lineTo(50, 100) // 把上面的moveTo改为lineTo
ctx3.lineTo(100, 100)
ctx3.stroke()
// 画三角形: 不在同一直线上的3个点用直线连起来就是三角形
var cnv4 = $$('canvas4')
var ctx4 = cnv4.getContext('2d')
ctx4.moveTo(50, 100)
ctx4.lineTo(150, 50) // 确定三个顶点坐标
ctx4.lineTo(150, 100)
ctx4.lineTo(50, 100)
ctx4.stroke()
// 画矩形:4个顶点坐标即可确定一个矩形
var cnv5 = $$('canvas5')
var ctx5 = cnv5.getContext('2d')
ctx5.moveTo(50, 50)
ctx5.lineTo(150, 50) // 确定4个顶点坐标
ctx5.lineTo(150, 100)
ctx5.lineTo(50, 100)
ctx5.lineTo(50, 50)
ctx5.stroke()
}