猿问

在同一个canvas里显示多个图形

代码:
html:

<canvas id="canvas1" width="800" height="150" style="border: 1px solid #ccc"></canvas>
<script src="js/close.js" type="text/javascript"></script>

js:

function $$(id) {

    return document.getElementById(id);

}


//绘制正多边形的封装函数

window.onload = function () {

    var cnv1 = $$("canvas1");

    var cxt1 = cnv1.getContext("2d");


    createPolygon(cxt1,3,300,75,50);

    createPolygon(cxt1,4,400,75,50);

    createPolygon(cxt1,5,500,75,50);

    createPolygon(cxt1,6,600,75,50);

    cxt1.fillStyle = "HotPink";

    cxt1.fill();

}


//n - 表示n边形;dx、dy - 中心坐标;size - 表示n边形的大小

function createPolygon(cxt, n, dx, dy, size) {

    cxt.beginPath();

    var degree = (2 * Math.PI) / n;

    for(var i=0;i<n;i++){

        var x = Math.cos(i * degree);

        var y = Math.sin(i * degree);

        cxt.lineTo(x * size + dx,y * size + dy);

    }

    cxt.closePath();

}

怎么可以让这几个多边形在同一个canvas里显示?求解答,谢谢。

撒科打诨
浏览 1393回答 2
2回答

一只斗牛犬

填充了才是图形,你光画线有什么用

潇潇雨雨

function $$(id) {&nbsp; &nbsp; return document.getElementById(id);}//绘制正多边形的封装函数window.onload = function () {&nbsp; &nbsp; var cnv1 = $$("canvas1");&nbsp; &nbsp; var cxt1 = cnv1.getContext("2d");&nbsp; &nbsp; cxt1.fillStyle = "HotPink";&nbsp; &nbsp; createPolygon(cxt1,3,300,75,50);&nbsp; &nbsp; createPolygon(cxt1,4,400,75,50);&nbsp; &nbsp; createPolygon(cxt1,5,500,75,50);&nbsp; &nbsp; createPolygon(cxt1,6,600,75,50);}//n - 表示n边形;dx、dy - 中心坐标;size - 表示n边形的大小function createPolygon(cxt, n, dx, dy, size) {&nbsp; &nbsp; &nbsp; cxt.beginPath();&nbsp; &nbsp; var degree = (2 * Math.PI) / n;&nbsp; &nbsp; for(var i=0;i<n;i++){&nbsp; &nbsp; &nbsp; &nbsp; var x = Math.cos(i * degree);&nbsp; &nbsp; &nbsp; &nbsp; var y = Math.sin(i * degree);&nbsp; &nbsp; &nbsp; &nbsp; cxt.lineTo(x * size + dx,y * size + dy);&nbsp; &nbsp; }&nbsp; &nbsp; cxt.closePath();&nbsp; &nbsp; cxt.fill();}
随时随地看视频慕课网APP
我要回答