<pre name="code" class="javascript"><pre name="code" class="html"><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style></style>
</head>
<body>
<canvas id="canvas" width="600" height="600" style="display: block; margin:50px auto;border: 1px solid #ddd;">
该浏览器不支持canvas标签;
</canvas>
</body>
<script>
/*canvas基于状态进行绘制图形*/
/* if(canvas.getContext("2d")){
}else{
alert("该浏览器不支持canvas标签")
}*/
var tangram = [ //创建一个数组,里面放置7个要绘制的对象,对象的属性包括:绘制点 颜色;
{p: [{x: 0, y: 0}, {x: 600, y: 0}, {x: 300, y: 300}], color: "#caff67"},
{p: [{x: 0, y: 0}, {x: 300, y: 300}, {x: 0, y: 600}], color: "#67becf"},
{p: [{x: 600, y: 0}, {x: 600, y: 300}, {x: 450, y: 450}, {x: 450, y: 150}], color: "#ef3d61"},
{p: [{x: 450, y: 150}, {x: 450, y: 450}, {x: 300, y: 300}], color: "green"},
{p: [{x: 300, y: 300}, {x: 450, y: 450}, {x: 300, y: 600}, {x: 150, y: 450}], color: "#a594c0"},
{p: [{x: 150, y: 450}, {x: 300, y: 600}, {x: 0, y: 600}], color: "#fe8ecc"},
{p: [{x: 600, y: 300}, {x: 600, y: 600}, {x: 300, y: 600}], color: "#f6ca29"}
];
window.onload = function () { //
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
for (var i = 0; i < tangram.length; i++) {
draw(tangram[i], context);
}
};
function draw(piece, cxt) {
cxt.beginPath();
cxt.moveTo(piece.p[0].x, piece.p[0].y);
for (var i = 1; i < piece.p.length; i++) {
cxt.lineTo(piece.p[i].x, piece.p[i].y);
}
cxt.closePath();
cxt.fillStyle = piece.color;
cxt.fill();
}
/*window.onload = function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(0,0);
context.lineTo(300,300);
context.lineTo(600,0);
context.fillStyle = "blue";//"rgb("0,10,100");
context.lineWidth = 5;
context.strokeStyle ="#e4393c";
context.fill();
context.stroke();
context.closePath();
}*/
</script>
</html>
canvas:利用js遍历绘制七巧板
最新推荐文章于 2022-01-13 16:16:49 发布