canvas基础2
一、绘制路径
let drawing = document.getElementById("drawing");
if (drawing.getContext) {
let context = drawing.getContext("2d");
context.beginPath();
context.arc(100, 100, 99, 0, 2 * Math.PI, false);
context.moveTo(194, 100);
context.arc(100, 100, 94, 0, 2 * Math.PI, false);
context.moveTo(100, 100);
context.lineTo(100, 15);
context.moveTo(100, 100);
context.lineTo(35, 100);
context.stroke();
}
二、绘制文本
context.font = "bold 14px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText("12", 100, 20);
context.font = "bold 14px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText("12", 100, 20);
context.textAlign = "start";
context.fillText("12", 100, 40);
context.textAlign = "end";
context.fillText("12", 100, 60);
let drawing = document.getElementById("drawing");
if (drawing.getContext) {
let context = drawing.getContext("2d");
let fontSize = 100;
context.font = fontSize + "px Arial";
while(context.measureText("Hello world!123aaaaa").width > 140) {
fontSize--;
context.font = fontSize + "px Arial";
}
context.fillText("Hello world!123aaaaa", 10, 10);
context.fillText("Font size is " + fontSize + "px", 10, 50);
}
三、变换
let drawing = document.getElementById("drawing");
if (drawing.getContext) {
let context = drawing.getContext("2d");
context.beginPath();
context.arc(100, 100, 99, 0, 2 * Math.PI, false);
context.moveTo(194, 100);
context.arc(100, 100, 94, 0, 2 * Math.PI, false);
context.translate(100, 100);
context.moveTo(0, 0);
context.lineTo(0, -85);
context.moveTo(0, 0);
context.lineTo(-65, 0);
context.stroke();
}
context.rotate(1);
let drawing = document.getElementById("drawing");
if (drawing.getContext) {
let context = drawing.getContext("2d");
context.beginPath();
context.arc(100, 100, 99, 0, 2 * Math.PI, false);
context.moveTo(194, 100);
context.arc(100, 100, 94, 0, 2 * Math.PI, false);
context.translate(100, 100);
context.rotate(1);
context.moveTo(0, 0);
context.lineTo(0, -85);
context.moveTo(0, 0);
context.lineTo(-65, 0);
context.stroke();
}
let drawing = document.getElementById("drawing");
if (drawing.getContext) {
let context = drawing.getContext("2d");
context.fillStyle = "#ff0000";
context.save();
context.fillStyle = "#00ff00";
context.translate(100, 100);
context.save();
context.fillStyle = "#0000ff";
context.fillRect(0, 0, 100, 200);
context.restore();
context.fillRect(10, 10, 100, 200);
context.restore();
context.fillRect(0, 0, 100, 200);
}