html5学习2:使用canvas画直线
1、画直线
在html5的canvas中画直线,需要以下步骤
像这样:
<script> context.beginPath(); context.moveTo(x,y); context.lineTo(x,y); context.stroke(); </script>完整的例子:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #myCanvas { border: 1px solid #9C9898; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(100, 150); context.lineTo(450, 50); context.stroke(); </script> </body> </html>完整演示:
更多demo:
2、直线的宽度为画出的直线设置线宽,必须在使用stroke之前。
<script> context.lineWidth = 5; </script>完整的代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #myCanvas { border: 1px solid #9C9898; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(100, 150); context.lineTo(450, 50); context.lineWidth = 15; context.stroke(); </script> </body> </html>完整演示:
3、直线的颜色如同直线的宽度一样,也需要在stroke之前使用。可以使用单词颜色、hex颜色以及rgb颜色3类。
<script> context.strokeStyle = 'blue'; </script>完整代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #myCanvas { border: 1px solid #9C9898; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(100, 150); context.lineTo(450, 50); context.lineWidth = 10; // set line color context.strokeStyle = '#ff0000'; context.stroke(); </script> </body> </html>完整演示:
4、直线的端点在html5中直线的端点可以是直角、圆角和尖角3类。如同直线的颜色一样,也需要在stroke之前使用。
像这样:
<script> context.lineCap = 'round'; </script>完整代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #myCanvas { border: 1px solid #9C9898; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // butt line cap (top line) context.beginPath(); context.moveTo(200, canvas.height / 2 - 50); context.lineTo(canvas.width - 200, canvas.height / 2 - 50); context.lineWidth = 20; context.strokeStyle = '#0000ff'; context.lineCap = 'butt'; context.stroke(); // round line cap (middle line) context.beginPath(); context.moveTo(200, canvas.height / 2); context.lineTo(canvas.width - 200, canvas.height / 2); context.lineWidth = 20; context.strokeStyle = '#0000ff'; context.lineCap = 'round'; context.stroke(); // square line cap (bottom line) context.beginPath(); context.moveTo(200, canvas.height / 2 + 50); context.lineTo(canvas.width - 200, canvas.height / 2 + 50); context.lineWidth = 20; context.strokeStyle = '#0000ff'; context.lineCap = 'square'; context.stroke(); </script> </body> </html>需要注意的是,在使用尖角、圆角的时候,直线的长度会增加线宽的一半的2倍,也就是会增加一倍线宽的长度。
本文部分代码摘自
【完】
文章声明:
文章评论(2):
#2