筆記:HTML5 canvas畫圖
畫線
const ctx = canvasEle.getContext("2d");
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x1, y1);
ctx.stroke();
ctx.closePath();
畫矩形
const ctx = canvasEle.getContext("2d");
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.strokeRect(x, y, w, h);
畫橢圓
const ctx = canvasEle.getContext("2d");
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
const wrad = w / 2.0, hrad = h / 2.0;
ctx.ellipse(x + wrad, y + hrad, wrad, hrad, rotate, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
畫字
const ctx = canvasEle.getContext("2d");
ctx.font = `${fontStyle} ${size}px ${fontFace}`;
const metrics = ctx.measureText(text);
ctx.fillStyle = color;
// 讓文字位置得中心點為x,y
const offX = metrics.width / 2.0;
const offY =
(metrics.actualBoundingBoxDescent - metrics.actualBoundingBoxAscent) / 2.0;
ctx.fillText(text, x - offX, y - offY);
清除畫布
const ctx = canvasEle.getContext("2d");
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvasEle.width, canvasEle.height);
ctx.restore();
留言