用canvas画七巧板 -- 练习canvas

简介: 用canvas画七巧板 -- 练习canvas

用canvas画七巧板 -- 练习canvas


canvas知道绘制路径后,加强这方面的理解,就试着画了个七巧板。

首先复习下这些知识点:

  • canvas.width
  • canvas.height
  • canvas.getContext('2d')
  • context.beginPath()
  • context.moveTo(x,y)
  • context.lineTo(x,y)
  • context.closePath(x,y)
  • context.stroke(x,y)
  • context.fill(x,y)
  • context.strokeStyle='#ddd'
  • context.lineWidth=3
  • context.fillStyle='#ddd'

然后用上面的这些实现如图所示的七巧板~

网络异常,图片无法展示
|

思路:将每片的路径和颜色都存放起来,然后遍历下就好了~~。

<canvas id="tutorial"></canvas>
<script>
  const canvas = document.getElementById("tutorial");
  const ctx = canvas.getContext("2d");
  canvas.width = 800;
  canvas.height = 800;
  const tangram = [
    { p: [ [0, 0], [800, 0], [400, 400] ], color: "#caff67" },
    { p: [ [0, 0], [400, 400], [0, 800] ], color: "#67becf" },
    { p: [ [800, 0], [800, 400], [600, 600], [600, 200] ], color: "#ef3d61"},
    { p: [ [600, 200], [600, 600], [400, 400] ], color: "#f9f51a" },
    { p: [ [400, 400], [600, 600], [400, 800], [200, 600] ], color: "#a594c0" },
    { p: [ [200, 600], [400, 800], [0, 800] ], color: "#fa8ecc" },
    { p: [ [800, 400], [800, 800], [400, 800] ], color: "#f6ca29" }
  ];
  const drawPiece = (piece, ctx) => {
    // 路径
    ctx.beginPath();
    var firstPoint = piece.p.shift(0);
    ctx.moveTo(...firstPoint);
    piece.p.forEach(point => ctx.lineTo(...point));
    ctx.closePath();
    // 状态
    ctx.fillStyle = piece.color;
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 3;
    // 绘制
    // 在既有填充也有描边的情况下,一般先fill在stroke
    ctx.fill();
    ctx.stroke();
  };
  tangram.forEach(piece => drawPiece(piece, ctx));
</script>

慕课上liuyubobobo老师,说canvas挺好的,可以细看看他的视频,也是demo来源

目录
相关文章
|
移动开发 前端开发 JavaScript
让自己也能使用Canvas
<canvas> 是 HTML5 新增的元素,可使用JavaScript脚本来绘制图形。例如:画图,合成照片,创建动画甚至实时视频处理与渲染。
让自己也能使用Canvas
|
3天前
|
前端开发 算法 计算机视觉
用canvas消除锯齿的方式
用canvas消除锯齿的方式
13 0
|
4月前
|
移动开发 前端开发 JavaScript
canvas详解00-认识canvas
canvas详解00-认识canvas
35 1
canvas详解00-认识canvas
|
移动开发 前端开发 JavaScript
Canvas2D基础
1. canvas内容就是上面这些了,就好比设计师能用的颜色就那么多,但是将颜色,图形组合起来,创意真的是无限的,canvas也是如此。 2. webGL是一个 对OpenGL ES 2.0浏览器实现接口,用于3D绘画,生产阶段最好不要用,可用于实验阶段。
210 0
|
存储 XML 前端开发
神奇的 Canvas
canvas是为了解决页面只能显示静态图片而出现的一种可以使用JavaScript绘制的HTML标签,它可以接受两个参数width和height(原来有三个,还有一个moz-opaque控制透明度,已经废弃了)
80 0
|
移动开发 前端开发 小程序
Canvas 2D详解
Canvas 2D详解
Canvas 2D详解
|
前端开发
canvas-缤纷纸片
第一次用canvas绘图,其实难度是挺大的,基于js和一些数学知识,还有参考了网上很多的例子,最终完成了demo。
1268 0
fbh
|
前端开发 HTML5 移动开发
分享一个canvas代码2
学习HTML5 Canvas这一篇文章就够了 HTML5 Canvas粒子效果文字动画特效DEMO演示 展现地址:http://csdn.
fbh
842 0
fbh
|
Web App开发 前端开发
分享一个canvas代码
首先需要已入jquery 然后直接运行 function project3D(x,y,z,vars){var p,d;x-=vars.
fbh
1021 0
|
前端开发
第156天:canvas(三)
一、变形 1.1 translate translate(x, y) ​ 用来移动 canvas 的原点到指定的位置 ​ translate方法接受两个参数。x 是左右偏移量,y 是上下偏移量,如右图所示。
955 0