1,我不需要学
CanvasAPI不需要学,不需要用,单纯的用来玩耍。
2,入门案例
结构。
<canvas id="app"></canvas>
表现。
#app {
outline: solid pink 2px;
}
行为。
app是canvas元素,
宽高可以直接设置。
pen是画笔,
可以由它生成各种各样的效果。
const app = document.getElementById('app');
app.width = 300;
app.height = 300;
const pen = app.getContext('2d');
pen.fillStyle = 'green';
pen.fillRect(0, 0, 300, 300);
pen.fillStyle = 'red';
pen.fillRect(0, 0, 100, 100);
效果:
3,兼容的写法
结构的兼容:
<canvas id="app">
浏览器不支持
</canvas>
行为的兼容:
const app = document.getElementById('app');
app.width = 300;
app.height = 300;
if (app.getContext) {
const pen = app.getContext('2d');
pen.fillStyle = 'green';
pen.fillRect(0, 0, 300, 300);
pen.fillStyle = 'red';
pen.fillRect(0, 0, 100, 100);
} else {
console.log("浏览器不支持")
}