学习canvas(初步入门)

canvas一些基础api用法

  1. 首先需要创建一个 canvas

<canvas id="canvas"></canvas>

  1. 然后获取到这个元素,可以用 Document.getElementById('canvas')

const canvas = document.getElementById("canvas");

  1. 然后拿到他的上下文对象ctx (然后可以在上下文的位置绘制内容)

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d");

getContext的方法签名中的contextType还有以下可选
"2d":2D绘图上下文,用于绘制二维图形。
"webgl":WebGL绘图上下文,用于绘制三维图形,利用OpenGL ES 2.0。
"webgl2":WebGL2绘图上下文,是WebGL的升级版,利用OpenGL ES 3.0。

  1. fillStyle 属性让长方形变成绿色。fillRect() 方法将它的左上角放在 (10, 10),把它的大小设置成宽 150 个单位高 100 个单位。

ctx.fillStyle = "green"; ctx.fillRect(10, 10, 150, 100);

  1. 这样就能看见一个绿色的长方形了

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial

posted @ 2024-07-08 16:26  卡优卡1255  阅读(40)  评论(0)    收藏  举报