canvas

1)实心矩形。

ctx.fillStyle = 'rgb(0,255,0)';

ctx.fillRect(10,20,50,50); // x,y,width,height

2)空心矩形。

ctx.strokeStyle = 'rgb(0,182,0)';

ctx.lineWidth = 5;

ctx.strokeRect(9,19,52,52);

3)线性渐变。

gradient = ctx.createLinearGradient(0,0,0,canvas.height);   //渐变起始点x1,y1,渐变终点x2,y2

gradient.addColorStop(0,'#fff');

gradient.addColorStop(1,'#000');

ctx.fillStyle = gradient;

ctx.fillRect(0,0,canvas.width,canvas.height);

4) 放射性渐变。

gradient = ctx.createRadialGradient(canvas.width/2,canvas.height/2,0,canvas.width/2,canvas.width/2,canvas.height/2,150);   //渐变起始点x1,y1,半径,渐变终点x2,y2,半径

gradient.addColorStop(0,'#fff');

gradient.addColorStop(1,'#000');

ctx.fillStyle = gradient;

ctx.fillRect(0,0,canvas.width,canvas.height);

5) 模式。canvas支持将图像、其他画布、视频做为源,然后在画布上平铺。但需要注意的是,必须要等到图片、视频下载完后才可以作为源使用。

var img = document.createElement("img");

img.src="a.png";

img.onload = function(){

ctx.fillStyle = ctx.createPattern(this,'repeat'); // repeat-x,preat-y,no-repeat

ctx.fillRect(0,0,canvas.width,canvas.height);

}

6) 画曲线。

ctx.beginPath();   // 开始绘图

ctx.arc(100,500,30,0,Math.PI*2,true);    // x坐标,y坐标,半径,开始角度,结束角度,是否顺时针

ctx.fill(); // 填充颜色

ctx.beginPath();

ctx.strokeStyle = "#c00";

ctx.lineWidth = 3;

ctx.arc(100,50,20,0,Math.PI,false);

ctx.stroke();   // 描线

7) 捕获图像。

canvas支持对图片的处理,最常用的为drawImage方法,虽然名为drawImage,但事实上,对于视频,也可以绘制出来,但要注意的是,绘制视频其实也只能绘制一帧至画布上,如果想在画布上绘制动画,需要定时重绘。需要注意的是drawImage方法中的源只能是通过http提供,不能通过本地文件系统提供。另外,受到同源规则的限制,它必须来自相同的域。

另外,canvas直接像素级操作,比如getImageData和putImageData方法。getImage方法接收4个参数,分别是x,y坐标,和width、height,返回的结果是个hash对象,包括height、width和data属性,其中data属性是一个数组,它包括rgba4个通道,并依次排列在数组中,也就是说,返回的数组是

[r1,g1,b1,a1,r2,g2,b2,a2,....]的形式,数组长度为像素个数的4倍。

putImageData接收三个参数,分别是像素数组,x,y坐标。

============================

var img = document.createElement('img');

img.src="a.png";

img.onload = function(){

ctx.canvas.width = img.width;

ctx.canvas.height = img.height;

ctx.drawImage(img,0,0);

var pixels = ctx.getImageData(0,0,img.width,img.height);

for(var i=0,n=pixels.data.length;i<n;i+=4){

     pixels.data[i+0] = 255 - pixels.data[i+0]; //red

     pixels.data[i+1] = 255 - pixels.data[i+2]; //green

     pixels.data[i+2] = 255 - pixels.data[i+1]; // blue

}

}

ctx.putImageData(pixels,0,0);

原文地址:https://www.cnblogs.com/cly84920/p/4426638.html