LayaBox

HTML5之Canvas

2016-03-28  本文已影响126人  刘涤生

Canvas

Canvas是HTML5新增的组件,它就是一块画布,可以用JavaScript在上画绘制各种图标、动画等。

Web页面增加画布

Canvas元素是一个标准的HTML5元素,可以直接在HTML5页面中添加<canvas>标签,如

<!DOCTYPE HTML>
<html>
<head>
    <title>Look what I Drew</title>
    <meta charset="utf-8">
</head>

<body>
    <canvas id="draw" width="600" height="200"></canvas>
</body>
</html>

width属性定义它在web页面中水平方向所占的像素,height定义了它在web页面中垂直方向所占的像素。

注意:上面的web页面无法显示画布的,除非你在画布上绘制了内容。

显示画布

现在找到一个证据,证明画布在我们的页面中确实存在。我们可以通过位canvas指定CSS样式,下面来增加一个简单的样式,为画布增加一个1像素宽的黑色边框。

<!DOCTYPE HTML>
<html>
<head>
    <title>Look what I Drew</title>
    <meta charset="utf-8">
    <!--指定样式-->
    <style>
        canvas{
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="draw" width="600" height="200"></canvas>
</body>
</html>

效果:

在画布上绘图

接下来我们开始在画布上绘制一个矩形。要画这个矩形,首先要确定矩形的位置,其次是矩形的大小。这里把矩形画在x=10像素、y=10像素的位置,让它的高度和宽度都等于100像素。

<!DOCTYPE HTML>
<html>
<head>
    <title>Look what I Drew</title>
    <meta charset="utf-8">
    <style>
        canvas{
            border: 1px solid black;
        }
    </style>

    <script>
        window.onload = function () {
            //在画布上画个矩形
            var canvas = document.getElementById('draw');
            var context = canvas.getContext("2d");
            context.fillRect(10,10,100,100);
        };
    </script>
</head>

<body>
    <canvas id="draw" width="600" height="200"></canvas>
</body>
</html>

失败处理

因为Canvas是HTML5中新增的特性,所以会遇到有些浏览器不支持的情况,这是我们就需要查看canvas对象中是否存在getContext方法:

<script>
    window.onload = function () {
        //在画布上画个矩形
        var canvas = document.getElementById('draw');
        //判断浏览器是否支持Canvas
        if (canvas.getContext) {
            console.info("you hava canvas");
            var context = canvas.getContext("2d");
            context.fillRect(10,10,100,100);
        } else {
            console.info("soory, no canvas support ApI");
        }


    };
</script>

此外我们还可以这样做:

<canvas id="draw" width="600" height="200">Please upgrade your browser!</canvas>

只要浏览器看到不认识的元素,默认行为就显示其中包含的文本。所以,不支持Canvas的浏览器看到<canvas>元素时,它们就会显示Please upgrade your browser!。另一方面,支持画布的浏览器会直接忽略画布标记之间的所有文本,所以不会显示这个文本。

实例演示

现在,我们开始通过一个实例来学习使用Canvas绘制矩形、圆、文本、图片等功能。先看看效果:

建立HTML,并增加form表单

先新建一个HTML的页面,并增加form表单控件

<!DOCTYPE HTML>
<html>
<head>
    <title>TweetShirt</title>
    <meta charset="utf-8">
    <style>
        canvas{
            border: 1px solid black;
        }
    </style>

    <script src = "tweetshirt.js">
    </script>
</head>

<body>
    <h1>TweetShirt</h1>
    <canvas id="tshirtCanvas" width="600" height="200">Please upgrade your browser to use TweetShirt!</canvas>

    <form>
        <p>
            <label for="backgroudColor">选择背景颜色: </label>
            <select id = "backgroundColor">
                <option value="white" selected="selected">白色</option>
                <option value="black">黑色</option>
            </select>
        </p>

        <p>
            <label for="shape">选择图形: </label>
            <select id = "shape">
                <option value="none" selected="selected">无</option>
                <option value="circles">圆形</option>
                <option value="squares">正方形</option>
            </select>
        </p>

        <p>
            <label for="foregroundColor">选择前景颜色: </label>
            <select id = "foregroundColor">
                <option value="black" selected="selected">黑色</option>
                <option value="white">白色</option>
            </select>
        </p>

        <p>
            <input type="button" id="previewButton" value="预览">
        </p>

    </form>
</body>
</html>

JavaScript处理表单控件

新建一个JavaScript文件tweetshirt.js,首先启动预览按钮,这样点击这个按钮时它就会调用一个JavaScript函数来处理Canvas绘制。

window.onload = function () {
    var button = document.getElementById("previewButton");
    button.onclick = previewHandler;
}

<!--预览点击事件-->
function previewHandler() {
    var canvas = document.getElementById("tshirtCanvas");
    var context = canvas.getContext("2d");

    //绘制图像之前,重置之前绘制的内容
    fillBackgroudColor(canvas,context);

    //查看界面选择了哪种颜色
    var selectObj = document.getElementById("shape");
    var index = selectObj.selectedIndex; //得到表单控件选项的编号的数组
    var shape = selectObj[index].value; //得到选项的值

    if (shape == "squares") {
        for(var squares = 0 ; squares < 20; squares++) {
            //绘制正方形
            drawSquare(canvas,context);
        }
    }

    if (shape == "circles") {
        for(var circles = 0 ; circles < 20; circles++) {
            //绘制圆
            drawCircle(canvas,context);
        }
    }
    //绘制文本
    drawText(canvas,context);
    //绘制图片
    drawImage(canvas,context);
}

function fillBackgroudColor(canvas,context) {
    var selectObj = document.getElementById("backgroundColor");
    var index = selectObj.selectedIndex;
    var bgColor = selectObj[index].value;

    //fillStyle保存画布上完成绘制时所用的颜色,它是一个属性而不是方法,所以需要设置而不是调用
    context.fillStyle = bgColor;
    context.fillRect(0,0,600,200);
}

绘制矩形

//画正方形
function drawSquare(canvas,context) {
    var w = Math.floor(Math.random() * 40);

    var x = Math.floor(Math.random() * canvas.width);
    var y = Math.floor(Math.random() * canvas.height);

    context.fillStyle = "lightblue";
    context.fillRect(x,y,w,w);
}

绘制线

//绘制线
function drawLine(canvas, context) {
    context.beginPath();
    context.moveTo(100, 150);
    context.lineTo(250, 75);
    context.lineTo(125, 30);
    context.closePath();
    context.lineWidth = 5;
    context.stroke();
    context.fillStyle = "red";
    context.fill();
}

绘制圆形

先来分析arc方法

context.arc(x,y,radius,startAngle,endAngle.direction);
//画圆形
function drawCircle(canvas,context) {

    var radius = Math.floor(Math.random() * 40);

    var x = Math.floor(Math.random() * canvas.width);
    var y = Math.floor(Math.random() * canvas.height);

    context.beginPath();
    context.arc(x,y,radius,0,degreeToRadians(360),true);
    context.fillStyle = "red";
    context.fill();
}

//度数转弧度
function degreeToRadians(degree) {
    return (degree * Math.PI) / 180;
}

绘制文本

//画文本
function drawText(canvas,context) {

    var selectObj = document.getElementById("foregroundColor");
    var index = selectObj.selectedIndex;
    var fgColor = selectObj[index].value;

    context.fillStyle = fgColor; //设置字体颜色
    context.font = "bold 1em sans-serif"; //设置字体
    context.textAlign = "left"; //设置对齐方式
    context.fillText("I saw this tweet",20,40); //填充文本

    context.font = "bold 1em sans-serif";
    context.textAlign = "right";
    context.fillText("and I got was this lousy t-shirt!",canvas.width-20,canvas.height-40);
}

绘制图片

function drawImage(canvas,context) {
    var image = new Image();
    image.src = "twitterBird.png";

    //表示图片加载完成,就执行这个函数
    image.onload = function () {
        context.drawImage(image,20,120,70,70);
    }
}

效果:

上一篇 下一篇

猜你喜欢

热点阅读