HTML5 Canvas

290 阅读2分钟

示例代码

image.png

image.png

Canvas 坐标

image.png

路径

image.png

image.png

圆形

image.png

arc() 方法的参数列表如下:

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
参数名类型说明
xNumber圆心的 x 坐标
yNumber圆心的 y 坐标
radiusNumber圆的半径
startAngleNumber圆弧的起始角度(以弧度为单位,0 表示 x 轴正方向)
endAngleNumber圆弧的结束角度(以弧度为单位)
anticlockwise(可选)Boolean指定弧线绘制方向,false(默认)为顺时针,true 为逆时针

image.png

文本

Canvas - 文本

使用 canvas 绘制文本,重要的属性和方法如下:

  • font - 定义字体。
  • fillText(text,x,y) - 在 canvas 上绘制实心的文本。
  • strokeText(text,x,y) - 在 canvas 上绘制空心的文本。

在 fillText 和 strokeText 方法中,最后两个参数分别表示文本的起始位置的 x 坐标 和 y 坐标。具体来说:

  • x: 文本的起始水平位置(相对于画布的左上角)。
  • y: 文本的起始垂直位置(相对于画布的左上角)。
var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

ctx.font="30px Arial";

ctx.fillText("w3cschool",10,50);

ctx.strokeText("w3cschool",10,100);

渐变

渐变可以填充在矩形, 圆形, 线条, 文本等等, 各种形状可以自己定义不同的颜色。

以下有两种不同的方式来设置Canvas渐变:

  • createLinearGradient(x,y,x1,y1) - 创建线条渐变。
  • createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变。

当我们使用渐变对象,必须使用两种或两种以上的停止颜色。

addColorStop() 方法指定颜色停止,参数使用坐标来描述,可以是 0 至 1。

使用渐变,设置 fillStyle 或 strokeStyle 的值为 gradient ,然后绘制形状,如矩形,文本,或一条线。

var c1=document.getElementById("myCanvas1");
var ctx1=c1.getContext("2d");

var c2=document.getElementById("myCanvas2");
var ctx2=c2.getContext("2d");
 
// 创建渐变
var grd1=ctx1.createLinearGradient(0,0,200,0);
grd1.addColorStop(0,"red");
grd1.addColorStop(1,"white");

// 创建渐变
var grd2=ctx2.createRadialGradient(75,50,5,90,60,100);
grd2.addColorStop(0,"red");
grd2.addColorStop(1,"white");
 

// 填充渐变
ctx1.fillStyle=grd1;
ctx1.fillRect(10,10,150,80);

// 填充渐变
ctx2.fillStyle=grd2;
ctx2.fillRect(10,10,150,80);

image.png

图像

image.png