Skip to main content

Canvas 技术笔记

· One min read
小卡
大家好,这里是好学爱摸鱼的小卡!

声明画布

var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var ctx = canvas.getContext("2d");

矩阵变化

ctx.tranlate(x, y); ctx.rotate(angle * Math.PI/180); ctx.scale(rate_x, rate_y); 画线 context.lineWidth = 2; // 确定线宽 ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(200,20); ctx.lineTo(120,120); ctx.closePath(); // draws last line of the triangle, from this point to the point started ctx.stroke(); 画正方形 ctx.rect(20, 20, 150, 100); ctx.stroke();

填充

ctx.rect(10, 10, 100, 100); ctx.fill(); or ctx.moveTo(20,20); ctx.lineTo(200,20); ctx.lineTo(120,120); ctx.closePath(); ctx.fill(); or ctx.fillRect(x, y , width, height);

画线并填充

正方形 context.fillStyle = "#009900"; context.fillRect(10,10, 100,100); context.strokeStyle = "#0000ff"; context.lineWidth = 5; context.strokeRect(10,10, 100,100);

清除

正方形 ctx.clearRect(x, y, width, height); 多边形 ctx.globalCompositeOperation = "souce-over"; // default ctx.globalCompositeOperation = "destination-out"; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(100,50); ctx.lineTo(50, 100); ctx.lineTo(0, 90); ctx.closePath(); ctx.fill();