canvas日常业务比较少接触,就这么说吧,虽然偏门,但一旦用起来,没有足够的只是储备,你根本玩不转!!赶紧学习吧
实现效果![请添加图片描述](https://i-blog.csdnimg.cn/direct/f9faa0020f2d4385a5aa056968f076aa.gif)
canvas 的特性
- 1.canvas 是一个矩形区域,可以控制其每一像素
- 2.canvas 的默认大小是 300*150,可以通过 css 控制其大小
- 3.canvas 标签中可以写 js 代码,直接操作 canvas 元素
canvas 的基本使用
drawRect();
function drawRect() {
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
//带边框处理边框变粗的代码
ctx.strokeRect(50.5, 50.5, 100, 100);
}
- 带边框处理边框变粗的代码,及描边和填充先后顺序
drawRect();
function drawRect() {
ctx.fillStyle = "red";
ctx.strokeStyle = "blue";
ctx.lineWidth = 10;
ctx.strokeRect(50.5, 50.5, 100, 100);
ctx.fillRect(50, 50, 100, 100);
ctx.fillRect(250, 50, 100, 100);
ctx.strokeRect(250.5, 50.5, 100, 100);
}
- lineJoin 属性
ctx.lineJoin = "miter"; //默认
ctx.lineJoin = "round"; //圆角
ctx.lineJoin = "bevel"; //斜角
- lineCap 属性
ctx.save();
//默认值buff
ctx.lineCap = "round";
ctx.moveTo(100, 100);
ctx.lineTo(250, 300);
ctx.stroke();
ctx.restore();
ctx.save();
ctx.lineCap = "square"; //高度多出来的部分,是lineWidth的宽度一般
ctx.moveTo(200, 100);
ctx.lineTo(350, 300);
ctx.stroke();
ctx.restore();
-
save() 和 restore() 属性
window.onload = function () {
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.rect(100, 100, 200, 200);
ctx.closePath();
ctx.stroke();
ctx.restore();
ctx.beginPath();
ctx.rect(300, 100, 200, 200);
ctx.closePath();
ctx.stroke();
};
案例实战
window.onload = function () {
const canvas = document.getElementById("mycanvas");
const clearBtn = document.getElementById("clear");
const color = document.getElementById("color");
const lineWidth = document.getElementById("lineWidth");
const ctx = canvas.getContext("2d");
canvas.onmousedown = function (e) {
var e = e || window.event;
const x = e.clientX - canvas.offsetLeft;
const y = e.offsetY - canvas.offsetTop;
ctx.beginPath();
ctx.strokeStyle = color.value;
ctx.lineWidth = lineWidth.value;
ctx.moveTo(x, y);
canvas.onmousemove = function (e) {
var e = e || window.event;
const x1 = e.clientX - canvas.offsetLeft;
const y1 = e.offsetY - canvas.offsetTop;
ctx.lineTo(x1, y1);
ctx.stroke();
};
canvas.onmouseup = function (e) {
canvas.onmousemove = null;
ctx.closePath();
};
};
clearBtn.addEventListener("click", function () {
// 画布清空,此处只能清理rect区域,无法清理path,需要加上ctx.beginPath();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
});
};