canvas api 速记

基本骨骼#

<canvas id="canvas" width=1000 height=1000 style="border: 1px black dotted"></canvas>

<script>
  var ctx = document.getElementById('canvas').getContext('2d');
</script>

矩形#

实心:

// 填充色 (默认为黑色)
ctx.fillStyle = 'darkSlateBlue';

// 规定画布左上角坐标为 (0, 0)
// 矩形左上角坐标 (0, 0)
// 矩形大小 100*100
ctx.fillRect(0, 0, 100, 100);

空心:

// 边框颜色 (默认黑色)
ctx.strokeStyle = 'darkSlateBlue';

// 规定画布左上角坐标为 (0, 0)
// 矩形左上角坐标 (0, 0)
// 矩形大小 100*100
ctx.strokeRect(0, 0, 100, 100);

圆形#

实心:

ctx.fillStyle = 'darkSlateBlue';

ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();

空心:

ctx.strokeStyle = 'darkSlateBlue';

ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();

线段#

ctx.strokeStyle = 'darkSlateBlue';

ctx.beginPath();
ctx.moveTo(100, 100); // 起点
ctx.lineTo(200, 200);
ctx.lineTo(300, 100);
// ctx.closePath();
ctx.stroke();

图像#

动态生成 img:

var img = new Image();

// 一定要等图片载入后(或者已经在缓存中了)才能用 drawImage 方法
img.onload = function() {
  // 左上角坐标 & 图像大小
  ctx.drawImage(img, 0, 0, 100, 56);
};

img.src = '0.jpg';

或者直接从 dom 中取:

var img = document.getElementById('myImg'); 
ctx.drawImage(img, 0, 0, 100, 56);

文字#

文字 的位置设定相对复杂,不像矩形、图像一样有个固定的左上角坐标,也不像圆一样有固定的圆心。文字的位置设置也是一个类似 (x, y) 形式的坐标,这个位置可以是文字的 4 个角,或者中心。

x 部分,蓝线(水平坐标)为 x 坐标所在位置(textAlign 属性):

ctx.font = "bold 80px serif"
ctx.textAlign = "start";  // 默认值为 start

ctx.fillStyle = 'darkSlateBlue';
// 文本内容、坐标
ctx.fillText('hello world', 0, 0);

y 部分,蓝线(垂直坐标)为 y 坐标所在位置 (textBaseline 属性):

ctx.font = "bold 80px serif"
ctx.textAlign = "start";  // 默认值为 start
ctx.textBaseline = "hanging"; // 默认值为 alphabetic

ctx.fillStyle = 'darkSlateBlue';
// 文本内容、坐标
ctx.fillText('hello world', 0, 0);

所以文字的位置共有 5*6=30 种。

fillText 方法不支持文本断行,即所有文本出现在一行内。所以,如果要生成多行文本,只有调用多次 fillText 方法。

空心的话用 stroke 即可。

其他 API#

属性:

  • lineWidth:stroke 的线条宽度 ctx.lineWidth = 2

方法:

  • clearRect: 清除某部分(矩形区域)画布 ctx.clearRect(0, 0, 100, 100)
  • measureText: 计算文本对象的宽度
  • translate
  • rotate

Read More#

原文地址:https://www.cnblogs.com/lessfish/p/5120873.html