1.canvas基础

1.canvas的引入

<canvas id="canvas" width="1024" height="768" style="border:1px solid #aaa;display: block;margin: 50px auto;">

这一行引入canvas设置了width和heigth设置画布宽高,style设置了边框颜色大小和内边距

canvas 元素本身是没有绘图能力的。所有的绘制工作必须在 JavaScript 内部完成:

var canvas = document.getElementById("canvas"); //获取对象
var context = canvas.getContext("2d"); //通过context画图

2.绘制直线


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
head>
<body>
    <canvas id="canvas" width="1024" height="768" style="border:1px solid #aaa;display: block;margin: 50px auto;">

    canvas>
    <script>
        window.onload = function(){
        //js事件网页加载好就执行
            var canvas = document.getElementById("canvas");
            canvas.width = 1024;
            canvas.height = 768;
            if(canvas.getContext("2d")){
      
                var context = canvas.getContext("2d");
            //使用context绘制
            }
            else{
      
                alert('当前浏览器不支持canvas,请更换浏览器');
            }

            //画三角形
            context.beginPath();
            context.moveTo(100, 100);
            context.lineTo(700, 700);
            context.lineTo(100, 700);
            context.lineTo(100, 100);
            context.closePath();
            context.fillStyle = "rgb(2, 100, 30);" //将图形设置为实心
            context.fill(); //显示出来实心图形
            context.lineWidth = 5;
            context.strokeStyle = "red";
            context.stroke(); //显示直线

            //画直线
            context.beginPath();
            context.moveTo(200, 100);
            context.lineTo(700, 600);
            ontext.closePath();
            context.strokeStyle = "black";
            context.stroke();

        }
    script>
body>
html>

因为画了两个图形为了不让状态机的设置相互影响通过beginpath和closepath来解决,这两个方法包围住点的设置,canvas的坐标轴是以左上角为原点,水平向右为x轴正方向,竖直向下为y轴正方向

3.绘制弧线

<script>
        window.onload = function(){
        //js事件网页加载好就执行
            var canvas = document.getElementById("canvas");
            canvas.width = 800;
            canvas.height = 800;
            var context = canvas.getContext("2d");
            //使用context绘制
            context.lineWidth = 5;
            context.strokeStyle = "#005588";
            //加个true就是逆时针了
            context.arc(300, 300, 200, 0, 1.5*Math.PI);//以点(300,300)为圆心,200为半径,从0开始顺时针画到1.5pi
            context.stroke();
        }
    script>

你可能感兴趣的:(HTML5游戏开发实战,canvas,html5)