Canvas - 画线
文章目录画线使用鼠标画线参考画线<!DOCTYPE html><html><head><meta charset="utf-8"><title>Canvas</title><style type="text/css">body {background-color: aquamarine;
·
画线
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<style type="text/css">
body {
background-color: aquamarine;
}
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script type="text/javascript">
window.onload = function(event) {
// console.log(this, event)
main()
}
function main() {
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
if (!ctx) return
ctx.beginPath()
ctx.strokeStyle = 'blue'
ctx.lineWidth = 2
ctx.moveTo(20, 20)
ctx.lineTo(200, 20)
ctx.stroke()
ctx.beginPath()
ctx.strokeStyle = 'green'
ctx.lineWidth = 4
ctx.moveTo(20, 20)
ctx.lineTo(100, 100)
ctx.stroke()
}
</script>
</body>
</html>
使用鼠标画线
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<style type="text/css">
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript">
window.onload = function(event) {
// console.log(this, event)
main()
}
function main() {
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
if (!ctx) return
let isDrawing = false
let x = 0
let y = 0
canvas.addEventListener('mousedown', e => {
x = e.layerX
y = e.layerY
isDrawing = true
})
canvas.addEventListener('mousemove', e => {
if (isDrawing) {
drawLine(ctx, x, y, e.layerX, e.layerY)
x = e.layerX
y = e.layerY
}
})
canvas.addEventListener('mouseup', e => {
console.log(e)
if (isDrawing) {
drawLine(ctx, x, y, e.layerX, e.layerY)
x = 0
y = 0
isDrawing = false
}
})
}
function drawLine(context, x0, y0, x1, y1) {
context.beginPath()
context.strokeStyle = 'black'
context.lineWidth = 1
context.moveTo(x0, y0)
context.lineTo(x1, y1)
context.stroke()
}
</script>
</body>
</html>
参考
更多推荐
已为社区贡献9条内容
所有评论(0)