html
<canvas ref="canvas" width="300" height="300"></canvas>
js
canvasInit(){
let canvas = this.$refs.canvas;
if(canvas.getContext) {
let ctx = canvas.getContext('2d');
ctx.fillRect(10,10,100,100);
ctx.strokeRect(110, 110, 100, 100);
ctx.clearRect(20,20,40,40);
}
},
图形
let canvas = this.$refs.canvas;
let ctx = canvas.getContext('2d');
ctx.fillRect(10,10,100,100);
ctx.strokeRect(110, 110, 100, 100);
ctx.clearRect(20,20,40,40);
ctx.rect(10,10, 120,100);
ctx.beginPath();
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.moveTo(10, 10);
ctx.lineTo(10, 10);
ctx.arc(75, 75, 50, 0, Math.PI * 2, true);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
圆角矩形函数
roundedRect(ctx, x, y, width, height, radius){
ctx.beginPath();
ctx.moveTo(x, y + radius);
ctx.lineTo(x, y + height - radius);
ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
ctx.lineTo(x + width - radius, y + height);
ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
ctx.lineTo(x + width, y + radius);
ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
ctx.lineTo(x + radius, y);
ctx.quadraticCurveTo(x, y, x, y + radius);
ctx.stroke();
}
颜色
ctx.fillStyle = "#ff9700";
ctx.strokeStyle = "#ff9700";
ctx.globalAlpha = 0.1;
let lingrad = ctx.createLinearGradient(0,0,150,150);
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(1, '#fff');
ctx.fillStyle = lingrad;
ctx.fillRect(10,10,130,130);
let radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(0.9, '#019F62');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function () {
var ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 150, 150);
};
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
文本
ctx.font = "20px serif";
ctx.fillText("hello world", 10, 30);
ctx.font = "20px serif";
ctx.strokeText("hello world", 10, 80);
变形
ctx.save();
ctx.restore();
ctx.translate(10, 10);
ctx.retate(45);
ctx.scale(x, y);