<body>
<!-- canvas画布的宽高设置需要使用width="500px" height="400px"属性,如果使用css会导致绘制内容变形 -->
<canvas id="canvasId" width="500px" height="400px" style="background-color: antiquewhite;">
低版本提示语,支持canvas标签的浏览器看不到
</canvas>
<script>
var canvas = document.getElementById('canvasId')
// 获取2d画布
var ctx = canvas.getContext('2d')
// 设置填充色
ctx.fillStyle='red'
// 填充一个矩形
ctx.fillRect(10,20,100,100)
console.log(ctx);
console.log(canvas);
</script>
</body>
<canvas id="myCanvasId" width="500" height="500" style="background-color: antiquewhite;">
请升级浏览器
</canvas>
<script>
var canvas = document.getElementById('myCanvasId')
var ctx = canvas.getContext('2d')
ctx.fillStyle = 'blue'
ctx.fillRect(100, 100, 100, 100)
var left = 100
setInterval(() => {
// 1.清屏
ctx.clearRect(0, 0, 500, 500)
// 2.更新
left++
// 3.渲染
ctx.fillRect(left, 100, 100, 100)
}, 10);
</script>
</body>
<body>
<canvas id="myCanvasId" width="500" height="500" style="background-color: antiquewhite;">
请升级浏览器
</canvas>
<script>
var canvas = document.getElementById('myCanvasId')
var ctx = canvas.getContext('2d')
// 定义一个类
function Rect(x, y, w, h, color) {
this.x = x
this.y = y
this.w = w
this.h = h
this.color = color
}
// 添加类方法
Rect.prototype.update = function () {
this.x++;
}
Rect.prototype.render = function() {
ctx.fillStyle=this.color
ctx.fillRect(this.x, this.y, this.w, this.h)
}
// 实例化
var r1 = new Rect(10, 100, 100, 100, 'blue')
var r2 = new Rect(10, 300, 100, 200, 'red')
setInterval(() => {
ctx.clearRect(0, 0, 500, 500)
// 第一个对象
r1.update()
r1.render()
// 第二个对象
r2.update()
r2.render()
}, 10);
</script>
</body>
<body>
<canvas id="myCanvasId" width="500" height="500" style="background-color: antiquewhite;">
请升级浏览器
</canvas>
<script>
var canvas = document.getElementById('myCanvasId')
var ctx = canvas.getContext('2d')
console.log(ctx);
// 画矩形填充
ctx.fillStyle='red'
ctx.fillRect(50,100,100,100)
// 画矩形框
ctx.strokeStyle='blue'
ctx.strokeRect(200,100,100,100)
// 画路径
// 1.打开路径
ctx.beginPath();
// 2.移动绘制点
ctx.moveTo(50, 400);
// 3.描述行进路径
ctx.lineTo(100, 450);
ctx.lineTo(200, 300);
// 4.闭合路径
ctx.closePath();
// 5.绘制路径
// ctx.strokeStyle = 'brown'
// ctx.stroke();
// 或
ctx.fillStyle = 'pink'
ctx.fill();
// 画弧度
// 1.开启路径
ctx.beginPath()
// 2.画圆弧
// 400, 400为起点, 50为半径, 0, 1为开始结束弧度(圆有2Pi个弧度约等于7个弧度), false为顺时针画;
ctx.arc(400, 400, 50, 0, 1, false);
// 3.绘制路径
// ctx.closePath()
// stroke()画实际路径,fill()会自动加colsePath()画出的是闭合路径。
ctx.strokeStyle='green'
ctx.stroke()
</script>
</body>