前言

本篇详细介绍canvas画布的API。说是详细介绍,也只是一些常用的API及简单实例和说明。LZ本人也还没有看完全部,下篇会介绍剩余的一些内容。

本篇的示例中,LZ加入了注释,为的是只简单介绍API确实挺无聊,也不那么容易理解,看代码看效果才最直接。

canvas APIs

canvas 基础api 介绍

在初始化Javascript函数中,用canvas标签的id获得canvasDOM对象,并用getContext() 方法获得这个canvas的“2d”上下文对象,之后使用上下文对象调用canvas API 画图。

直线

画直线的功能可以用 beginPath(), moveTo(), lineTo() 和 stroke() 几个方法的组合来实现。

方法 beginPath() 定义了一个新的路径绘制动作的开始。

方法 moveTo() 为指定点创建了一个新的子路径,我们可以把

moveTo() 方法看成用来定位绘图鼠标用的(直线的起点,因为所有画线都和它相关,我们称之为上下文点)。

方法 lineTo() 从鼠标定位点,到方法参数中指定的点之间画一条直线。

方法 stroke() 为所画的线赋予颜色,并使其可见。如果没有特别的指定颜色的话,则默认使用黑色画直线。

上下文对象context的属性

 context.lineWidth = 5; //设置宽度

 context.strokeStyle = 'blue'; //设置颜色

 context.lineCap = 'round'; //设置直线终点样式,可选值butt(默认值),round,和square

 示例如下 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>直线</title>

    <script>
        window.onload = function () {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");

            // 最上面的线是butt样式
            context.beginPath();
            context.moveTo(200, canvas.height / 2 - 50);
            context.lineTo(canvas.width - 200, canvas.height / 2 - 50);
            context.lineWidth = 10;
            context.strokeStyle = "#ff0000";
            context.lineCap = "butt";
            context.stroke();

            // 中间的线是round样式
            context.beginPath();
            context.moveTo(200, canvas.height / 2);
            context.lineTo(canvas.width - 200, canvas.height / 2);
            context.lineWidth = 15;
            context.strokeStyle = "#00ff00";
            context.lineCap = "round";
            context.stroke();

            // 最下面的是square样式
            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>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>
View Code

相关文章:

  • 2021-09-15
  • 2021-07-31
  • 2021-07-27
  • 2021-06-26
  • 2021-10-31
  • 2022-01-22
  • 2022-12-23
猜你喜欢
  • 2021-11-30
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-22
相关资源
相似解决方案