您现在的位置:首页 >> 前端 >> 内容

canvas绘制坐标系

时间:2016/12/10 13:41:00 点击:

  核心提示:!DOCTYPE htmlhtml lang=enheadmeta charset=utf-8/headbodyp id=containercanvas id=cavsElem您的浏览器不支持,请升级...
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <p id="container">
            <canvas id="cavsElem">
                您的浏览器不支持,请升级浏览器
            </canvas>
        </p>
        <script>
        (function(){
            var canvas = document.getElementById('cavsElem');
            var ctx = canvas.getContext("2d");
 
            canvas.width = 600;
            canvas.height = 600;
            canvas.style.border = '1px solid #000';
 
            // ctx.beginPath();
            // ctx.moveTo(0, 0);
 
            // ctx.closePath();
            // ctx.stroke();
            //绘制x轴 
            var x0 = 100;
            var y0 = 400;
            var maxHeight  = 300;
            var arrowWidth = 10;
            ctx.beginPath();
            ctx.strokeStyle = 'blue';
            ctx.moveTo(x0,y0);
            ctx.lineTo(500, 400);
            //往上面画箭头
            ctx.lineTo(500 - arrowWidth,400-arrowWidth);
            ctx.moveTo(500,400);
            ctx.lineTo(500 - arrowWidth,400+arrowWidth); 
            ctx.stroke();
 
            //绘制y轴
            ctx.beginPath();
            ctx.strokeStyle = 'orange';
            ctx.moveTo(x0,y0);
            ctx.lineTo(100, 0);
            ctx.lineTo(100-arrowWidth, arrowWidth);
            ctx.moveTo(100, 0);
            ctx.lineTo(100+arrowWidth,arrowWidth);
            ctx.stroke();
 
            //绘制线段
            var data = [.4,.5,.8,.7];
            var pointWidth = 400 / (data.length+1);
            ctx.beginPath();
            ctx.strokeStyle = 'blue';
            for(var i = 0;i<data.length;i++){
                var x = x0 + (i+1)*pointWidth;
                var y = y0 - data[i]*maxHeight;
                ctx.lineTo(x, y);
 
                ctx.stroke();
            }
 
        }());
        </script>
    </body>
</html>

结果如图:
canvas绘制坐标系

Tags:CA AN NV VA 
作者:网络 来源:一笑的博客