HTML5绘图学习记录
首先先要导入jquery.min.js
1.绘制矩形,线条,圆形
//获取canvas对象
var canvas = $("#mycanvas");
//的到2D context
var context = canvas.get(0).getContext("2d");
//矩形
context.fillStyle = "rgb(255,0,0)";
context.strokeStyle = "rgb(0,255,0)";
context.fillRect(40,40,100,100);
context.strokeRect(140,140,100,100);
//直线
context.beginPath();
context.moveTo(240,240);
context.lineTo(600,500);
context.closePath();
context.stroke();
//绘制圆形
context.beginPath();
context.arc(500,500,50,0,Math.PI/2,false);
context.lineTo(500,500);
context.closePath();
context.stroke();
//绘制字体
var text = "this is html5";
context.font = "italic 30px serif";
context.fillText(text,40,300);
context.lineWidth = 1;
context.strokeText(text,40,400);
//擦除操作
context.clearRect(200,200,100,100);
//擦除操作
context.clearRect(200,200,100,100);
//context.clearRect(0,0,canvas.width(),canvas.height());
//重置所有canvas上的元素
canvas.attr("width",canvas.width());
canvas.attr("height",canvas.height());
2.绘图状态的保存,画布变换,阴影,渐变和贝塞尔曲线
保存和应用就是一个对栈进行存取的操作,存的是画布的状态信息,如颜色,阴影,变换信息等等,先进后出,后进先出
context.save();
context.restore();
变换,对画布的操作,只对之后绘制的图形产生影响,可以把画布当成有多个图层,每次绘制都会新开一个图层,而变换就是对之后新开图层产生影响,绘制目标完后可以对画布进行还原
//平移
context.translate(100,100);
//缩放,注意缩放中心
context.scale(1,1.5);
//缩放,注意旋转中心
context.rotate(Math.PI/12);
//全局阿尔法值
context.globalAlpha = 0.5;
//合成模式,PS上的混合模式
context.globalCompositeOperation = "xor";
渐变的应用
//线性渐变
context.restore();
var gradient = context.createLinearGradient(0,0,0,canvas.height());
gradient.addColorStop(0,"rgb(0,0,0)");
gradient.addColorStop(1,"rgb(255,0,0)");
context.fillStyle = gradient;
context.fillRect(100,100,100,100);
//放射渐变
var canvasCentreX = canvas.width()/2;
var canvasCentreY = canvas.height()/2;
var gradient = context.createRadialGradient(canvasCentreX,canvasCentreY,0,canvasCentreX,canvasCentreY,250);
gradient.addColorStop(0,"rgb(0,0,0)");
gradient.addColorStop(1,"rgb(150,150,150)");
context.fillStyle = gradient;
贝塞尔曲线
//一阶贝塞尔曲线
context.lineWidth = 15;
context.beginPath();
context.moveTo(200,200);
context.quadraticCurveTo(350,200,450,450);
context.stroke();
//三阶贝塞尔曲线
context.lineWidth = 15;
context.beginPath();
context.moveTo(200,200);
context.bezierCurveTo(350,200,450,450,800,500);
context.stroke();
3.把绘制的图像导出,并应用到其他地方
var dataURL = canvas.get(0).toDataURL();
var img = $("<img></img>");
img.attr("src",dataURL);
canvas.replaceWith(img);
4.对图片进行处理
在画布上绘制图片
var image = new Image();
image.src = "example.jpg";
$(image).load(function(e) {
//显示图像
context.drawImage(image,0,0);
});