Canvas基本知识
用<canvas>标签,指定width和height属性,一般还要指定id属性以供js使用。
<canvas width="800" height="600" id="canvas">
你的浏览器不支持canvas
</canvas>
默认的width是300,height是150
注意canvas的css里的width和height和标签上的width以及height是不同的,浏览器会把标签上的大小缩放到css里设置的大小上,所以一般不需要设置css里的width和height。
canvas也就三个方法
- getContext - 一般就传入'2d'参数
- toDataURL(type, quality) - type默认为image/png,也可以指定别的格式,quality是一个0~1.0的数值,用在JPEG格式上,得到的结果是一个data:image/png;base64 xxxx这样的字符串,可以直接置给<img>的src
- toBlob(callback, type, quality) - 创建canvas元素图像文件的Blob对象,type默认也是image/png,最后一个也是quality,跟上一个方法一样
getContext获得的是一个CanvasRenderingContext2D对象,以下简称context,含有如下的属性
- canvas
- fillStyle
- font
- globalAlpha
- globalCompsiteOperation
- lineCap
- lineWidth
- lineJoin
- miterLimit
- shadowBlur
- shadowColor
- shadowOffsetX
- shadowOffsetY
- strokeStyle
- textAlign
- textBaseline
context含有两个方法save( )和restore( ),用来保存和恢复绘制时设置的上述属性,它是一个栈的数据结构。绝大多数情况下,对context的设置都要包裹在save()和restore()之间。
如果想要对context进行方法功能增强,那就在CanvasRenderingContext2D.prototype上添加方法。
canvas的原点坐标在左上角。
canvas的事件处理没有什么特别的,因为往下不存在DOM了,所以事件都要挂在canvas上,以下一段代码常用来进行事件坐标和canvas坐标的转换,同时考虑了CSS设置width和height的情况。
function windowToCanvas(canvas, x, y){
var bbox = canvas.getBoundingClientRect();
return {
x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height)
};
}
下面是一个根据鼠标移动画辅助线的例子,用到上面的方法
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
canvas.addEventListener("mousemove", e => {
let loc = windowToCanvas(canvas, e.clientX, e.clientY);
drawLines(loc)
});
function drawLines(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, loc.y);
context.lineTo(canvas.width, loc.y);
context.stroke();
context.beginPath();
context.moveTo(loc.x, 0);
context.lineTo(loc.x, canvas.height);
context.stroke();
}
PS:请复习一下中学数学,特别关于三角函数和向量的知识
矩形绘制
- clearRect(x, y, width, height)
- strokeRect(x, y, width, height)
- fillRect(x, y, width, height)
跟strokeRect有关的属性有
- strokeStyle
- lineWidth
- lineJoin
- miterLimit
跟fillRect有关的属性有
- fillStyle
渐变
- createLinearGradient(x0, y0, x1, y1) - 从(x0, y0)到(x1, y1)的线性渐变,用返回对象的addColorStop( )方法来增加颜色
- createRadialGradient(x0, y0, r0, x1, y1, r1) - 从(x0, y0)点周围r0宽度向(x1, y1)周围r1宽度放射渐变,也用返回对象的addColorStop( )方法来增加颜色
注意放射渐变可以不是一个矩形
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
gradient = context.createRadialGradient(
canvas.width / 2, canvas.height, 10,
canvas.width / 2, 0, 100);
gradient.addColorStop(0, 'blue&