PHP前端开发

html5 Canvas基本特性的示例代码分享

百变鹏仔 2个月前 (10-18) #H5教程
文章标签 示例

html5 canvas 介绍

canvas的基本属性与方法:width,height,getContext()等;

通过widthheight来获取和设置当前canvas的宽度、高度;

通过getContext()方法来获取当前画布的绘图环境(context);

context=canvas.getContext("2d");

立即学习“前端免费学习笔记(深入)”;

context包含了我们需要的,在canvas上绘图的所有方法及属性;

context的笛卡尔坐标系统中,canvas的左上角为原点;从原点往右为X轴的正向,往下为Y轴的正向;

关于坐标的例子:

<!DOCTYPE html><html>    <head>        <meta charset="utf-8" />        <title>s3</title>        <script type="text/javascript" src="../script/modernizr-latest.js"></script>        <script type="text/javascript">            window.addEventListener("load", eventWindowLoaded, false);            var Debugger = function() {            };            Debugger.log = function(message) {                try {                    console.log(message);                } catch (exception) {                    return;                }            }            function eventWindowLoaded() {                canvasApp();            }            function canvasSupport() {                return Modernizr.canvas;            }            function eventWindowLoaded() {                canvasApp();            }            function canvasApp() {                if(!canvasSupport()) {                    return;                }                var theCanvas = document.getElementById("canvasOne");                var context = theCanvas.getContext("2d");                function drawScreen() {                    //以下代码来源于<http://www.cnblogs.com/nothingbrother/archive/2011/12/23/2299856.html>for(var x = 0.5; x < 550; x += 10) {                        context.moveTo(x, 0);                        context.lineTo(x, 400);                    }                    for(var y = 0.5; y < 400; y += 10) {                        context.moveTo(0, y);                        context.lineTo(550, y);                    }                    context.strokeStyle = "#cecece";                    context.stroke();                    context.beginPath();                    context.moveTo(50, 150);                    context.lineTo(300, 150);                    context.moveTo(250, 100);                    context.lineTo(300, 150);                    context.moveTo(300, 50);                    context.lineTo(250, 100);                    context.moveTo(450, 200);                    context.lineTo(300, 50);                    /*symmetry*/                    context.moveTo(50, 250);                    context.lineTo(300, 250);                    context.moveTo(250, 300);                    context.lineTo(300, 250);                    context.moveTo(300, 350);                    context.lineTo(250, 300);                    context.moveTo(450, 200);                    context.lineTo(300, 350);                    /*end*/                    context.moveTo(50, 150);                    context.lineTo(50, 250);                    /*write coordinate*/                    context.font = "bold 12px sans-serif";                    context.fillText("( 0 , 0 )", 8, 5);                    context.fillText("(50, 150)", 58, 155);                    context.fillText("(300, 150)", 308, 155);                    context.fillText("(250, 100)", 258, 105);                    context.fillText("(300, 150)", 308, 155);                    context.fillText("(300, 50)", 308, 55);                    context.fillText("(50, 250)", 58, 255);                    context.fillText("(300, 250)", 308, 255);                    context.fillText("(250, 350)", 258, 355);                    context.fillText("(450, 200)", 458, 205);                    context.strokeStyle = "#f00";                    context.stroke();                }                drawScreen();            }        </script>    </head>    <body>        <div style="position: absolute; top: 50px; left: 50px;">            <canvas id="canvasOne" width="550" height="400">                Your browser does not support HTML5 Canvas.            </canvas>        </div>    </body></html>

context的所有属性及方法都是与current state结合使用;

我们在真正理解Canvas是如何工作的之前,current state是必须要掌握的一个概念;

current state 实事上是一个绘图状态的堆栈,这个堆栈从全局范围内适用于整个canvas;

我们可以操作如下一些状态:

Transformation matrix(变换矩阵)

Methods:scale, rotate, transform, and translate

Clipping region(区域裁剪)

Method:clip()

Properties of the context(context属性)

Properties: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, line Join, miterLimit, shadowOffsetX, shadowOffsetY,shadowBlur, shadowColor, global CompositeOperation, font, textAlign, and textBaseline.

先简单了解一下,会在以后的文章中对这些属性、方法的使用,慢慢剖析;

国外[oreilly]编写的一个小程序(猜字母):

<!DOCTYPE html><html>    <head>        <meta charset="utf-8" />                <title>s1</title>                <script type="text/javascript" src="../script/modernizr-latest.js"></script>        <script type="text/javascript">            window.addEventListener("load", eventWindowLoaded, false);            function eventWindowLoaded() {                canvasApp();            }            var Debugger = function() {            };            Debugger.log = function(message) {                try {                    console.log(message);                } catch (exception) {                    return;                }            }                        function canvasSupport() {                return Modernizr.canvas;            }            function eventWindowLoaded() {                canvasApp();            }            function canvasApp() {                var guesses = 0;                var message = "Guess The Letter From a (lower) to z (higher)";                var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];                var today = new Date();                var letterToGuess = "";                var higherOrLower = "";                var lettersGuessed;                var gameOver = false;                if(!canvasSupport()) {                    return;                }                var theCanvas = document.getElementById("canvasOne");                var context = theCanvas.getContext("2d");                initGame();                function initGame() {                    var letterIndex = Math.floor(Math.random() * letters.length);                    letterToGuess = letters[letterIndex];                    guesses = 0;                    lettersGuessed = [];                    gameOver = false;                    window.addEventListener("keyup", eventKeyPressed, true);                    drawScreen();                }                function eventKeyPressed(e) {                    if(!gameOver) {                        var letterPressed = String.fromCharCode(e.keyCode);                        letterPressed = letterPressed.toLowerCase();                        guesses++;                        lettersGuessed.push(letterPressed);                        if(letterPressed == letterToGuess) {                            gameOver = true;                        } else {                            letterIndex = letters.indexOf(letterToGuess);                            guessIndex = letters.indexOf(letterPressed);                            Debugger.log(guessIndex);                            if(guessIndex < 0) {                                higherOrLower = "That is not a letter";                            } else if(guessIndex > letterIndex) {                                higherOrLower = "Lower";                            } else {                                higherOrLower = "Higher";                            }                        }                        drawScreen();                    }                }                function drawScreen() {                    //Background                    context.fillStyle = "#ffffaa";                    context.fillRect(0, 0, 500, 300);                    //Box                    context.strokeStyle = "#000000";                    context.strokeRect(5, 5, 490, 290);                    context.textBaseline = "top";                    //Date                    context.fillStyle = "#000000";                    context.font = "10px _sans";                    context.fillText(today, 150, 10);                    //Message                    context.fillStyle = "#FF0000";                    context.font = "14px _sans";                    context.fillText(message, 125, 30);                    //Guesses                    context.fillStyle = "#109910";                    context.font = "16px _sans";                    context.fillText(&#39;Guesses: &#39; + guesses, 215, 50);                    //Higher Or Lower                    context.fillStyle = "#000000";                    context.font = "16px _sans";                    context.fillText("Higher Or Lower: " + higherOrLower, 150, 125);                    //Letters Guessed                    context.fillStyle = "#FF0000";                    context.font = "16px _sans";                    context.fillText("Letters Guessed: " + lettersGuessed.toString(), 10, 260);                    if(gameOver) {                        context.fillStyle = "#FF0000";                        context.font = "40px _sans";                        context.fillText("You Got It!", 150, 180);                    }                }            }        </script>    </head>    <body>        <div style="position: absolute; top: 50px; left: 50px;">            <canvas id="canvasOne" width="500" height="300">                Your browser does not support HTML5 Canvas.            </canvas>        </div>    </body></html>