- canvas元素本身并不会绘制图形,相当于一张空画布。如果你想在画布上进行绘制,那么必须通过JavaScript脚本进行绘制。
- 大多数现代浏览器都是支持Canvas的,比如 Firefox, safari, chrome, opera的最近版本以及IE9都支持.
- 在 HTML 页面上定义 canvas 元素与定义其他普通元素并无任何不同,它吃了可以指定 id, style ,class ,hidden 等通用属性之外,还可以设置 width 和 height 两个属性。
<style> #canvas{ width: 400px; height: 400px; border: 1px solid #ccc; } </style> <canvas id="canvas" width="400px" height="400px"> 画布 </canvas>
-
获取 canvas 元素对应的 DOM 对象,这必须是一个 canvas 对象
调用 canvas 对象的 getContext( ) 方法,该方法返回一个 canvasRenderingContext2D 对象,该对象可以绘制图形。
调用 canvasRenderingContext2D 对象的方法进行绘图。// 获取画布 const canvas =document.getElementById("canvas") // 绘制上下文 const ctx=canvas.getContext("2d") const drawCircle= (ctx, cx, cy, r)=>{ ctx.save() ctx.beginPath() //开始的位置 ctx.strokeStyle = "blue"; //描边 ctx.arc(cx, cy, r, 0, Math.PI *2) //画弧 ctx.stroke() //描边 ctx.closePath() //结束位置 ctx.restore() } drawCircle(ctx,100, 100, 50) //画笔自身的是不存储画过的圆
最终的结果:通过canvas绘制出来的圆○:是圆位于canvas坐标(100,100)的位置,半径为50.
Canvas的初步了解
最新推荐文章于 2024-06-07 23:26:45 发布