HTML5 Convas APIs方法详解

2020-04-24 18:53:51易采站长站整理

Web服务器,然后请求访问解决此问题。并且,涉及到的图像,JS和
HTML必须是来自同一个域名。不过,IE9可以通过本地文件访问。
一个例子如下:

复制代码
//获取一个像素区域
var imageData = context.getImageData(0, 0, 3, 3); // 3×3
grid</p>
<p>var width = imageData.width;
//特定像素在像素区域的位置
var x = 2;
var y = 2;
//绿颜色在像素数组中对应元素的索引
var pixelRedindex = ((y-1)*(width*4))+((x-1)*4);
var pixelGreenindex = pixelRedindex + 1;
var pixelBlueindex = pixelRedindex + 2;
var pixelAlphaindex = pixelRedindex + 3; </p>
<p>var pixel = imageData.data; // CanvasPixelArray </p>
<p>var red = pixel[pixelRedindex];
var green = pixel[pixelGreenindex];
var blue = pixel[pixelBlueindex];
var alpha = pixel[pixelAlphaindex];

☆ context.createImageData(w, h)

产生一个大小为(w, h)的ImageData对象,ImageData对象的意义
同getImageData()所获取的ImageData对象。

☆ context.putImageData(ImageData, x, y, x1, y1, w, h)

将一个ImageData对象绘制到canvas上(x, y)处。后四个参数是可
选参数,用于设定一个裁剪矩形的位置和大小。

☆ context.createLinearGradient(x1, y1, x2, y2)

在(x1, y1)和(x2, y2)之间产生线性渐变。如:

复制代码
var gradientName = context.createLinearGradient(-5, -50,
5, -50);

☆ Gradient.addColorStop(offset, color)

用于渐变中,在不同的位置设置渐变颜色。 The color argument
is the color you want to be applied in the stroke or fill at
the offset position. The offset position is a value between
0.0 and 1.0, representing how far along the gradient line
the color should be reached. 如:

gradientName.addColorStop(1, ‘#552200’);

其中color可用CSS中的rgba(r,g,b,a)函数来产生透明渐变,如:

复制代码
//产生50%的颜色透明渐变
gradientName.addColorStop(0.2, ‘rgba(0, 0, 0, 0.5)’);

☆ context.createRadialGradient(x0, y0, r0, x1, y1, r1)

在两个圆之间产生放射渐变区域。The first three arguments
represent a circle centered at (x0, y0) with radius r0, and
the last three arguments represent a second circle centered
at (x1, y1) with radius r1. The gradient is drawn across the
area between the two circles.

☆ context.createPattern(img, ‘repeatPattern’)

用一个图像img产生重复类型为repeatPattern的某路径的
strokeStyle样式或填充的fillStyle样式。repeatPattern的值可以
取repeat、repeat-x、repeat-y和no-repeat之一。如:

复制代码
context.strokeStyle = context.createPattern(gravel,