https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics
画布上下文:var ctx = canvas.getContext(‘2d’);
2D 画布基础
画布左上角的坐标是(0, 0),横坐标(x)轴向右延伸,纵坐标(y)轴向下延伸。
ctx.fillStyle = 'rgb(255, 0, 0)';ctx.fillRect(50, 50, 100, 150);
左边和顶边与画布边缘距离均为 50 像素(由前两个参数指定),宽 100 像素、高 150 像素(由后两个参数指定)。
var canvas = document.querySelector('.myCanvas');var width = canvas.width = window.innerWidth;var height = canvas.height = window.innerHeight;var ctx = canvas.getContext('2d');ctx.fillStyle = 'rgb(0, 0, 0)';ctx.fillRect(0, 0, width, height);ctx.fillStyle = 'rgb(255, 0, 0)';ctx.fillRect(50, 50, 100, 150);ctx.fillStyle = 'rgba(0, 255, 0,.5)';ctx.fillRect(75, 75, 100, 100);ctx.strokeStyle = 'rgb(255, 255, 255)';ctx.strokeRect(25, 25, 175, 200);ctx.lineWidth = 5;
矩形:
ctx.fillStyle = 'rgb(0, 255, 0)';ctx.fillRect(75, 75, 100, 100);
描边类似于border
在上文的 JS 代码的末尾添加以下代码:
ctx.strokeStyle = 'rgb(255, 255, 255)';ctx.strokeRect(25, 25, 175, 200);
默认的描边宽度是 1 像素,可以通过调整
lineWidth属性(接受一个表示描边宽度像素值的数字)的值来修改。在上文两行后添加以下代码:ctx.lineWidth = 5;
绘制路径
beginPath():在钢笔当前所在位置开始绘制一条路径。在新的画布中,钢笔起始位置为 (0, 0)。moveTo():将钢笔移动至另一个坐标点,不记录、不留痕迹,只将钢笔“跳”至新位置。fill():通过为当前所绘制路径的区域填充颜色来绘制一个新的填充形状。stroke():通过为当前绘制路径的区域描边,来绘制一个只有边框的形状。
