前端H5 canvas 常用API(-)

前端后台开发
后台开发 前端开发
女生学前端好还是后台开发

即时模式

var cav= document.getElementById(‘canvas’) //获取canvas DOM元素
var context= cav.getContext(‘2d’) //创建一个2D画布 之后直接引用context调用对应的对象 getContext()所有对象要通过该对象进行

cav.toDataURL() //返回位图字符串 默认的 images/png 可选 ‘image/jpeg’

context.fillStyle=” #ffffaa” //填充颜色

context.fillRect(X左上,Y左上,宽,高) //绘制实心形状矩形

context.strokeStyle = “#000” //描边颜色

context.strokeRect(X左上,Y左上,宽,高)//绘制空心矩形 默认是黑色

context.clearRect(X左上,Y左上,宽,高) //清楚指定区域 并且完全透明

context.font=”20px SimSum” //设置字体大小

context.textBaseline =’top’ //字体对其方式

context.fillText(‘hello world’,X,Y) //绘制文字

context.lineWidth=10 ;//线的宽度

context.lineCap = ‘butt’ //定义上下文 线的端点 默认 butt , round square 状态堆栈

context.lineJoin = ‘miter’ //定义两条线相交产生的拐角 默认值 mi 在连接处边缘延长相接 bevel 对角线斜角 round 连接处是一个圆 状态堆栈

context.beginPath()//开始路径

stroke() 方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径。默认颜色是黑色。

context.closePath()//结束路径

html 代码

<!doctype html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title>Ch2Ex3 Basic Line Joins</title>
    <script type=”text/javascript”>
        window.addEventListener(‘load’, eventWindowLoaded, false);
        function eventWindowLoaded() {
            canvasApp();
        }
        function canvasApp() {
            var theCanvas = document.getElementById(‘canvas’);
            if (!theCanvas || !theCanvas.getContext) {
                return;
            }
            var context = theCanvas.getContext(‘2d’);
            if (!context) {
                return;
            }
            drawScreen();
            function drawScreen() {
                //round end. bevel join, at top left of canvas
                context.strokeStyle = “black”; //need list of available colors
                context.lineWidth = 10;
                context.lineJoin = ‘bevel’;
                context.lineCap = ’round’;
                context.beginPath();
                context.moveTo(0, 5);
                context.lineTo(25, 5);
                context.lineTo(25, 25);
                context.stroke();
                context.closePath();
                //round end, bevel join, not at top or left of canvas
                context.beginPath();
                context.moveTo(10, 50);
                context.lineTo(35, 50);
                context.lineTo(35, 75);
                context.stroke();
                context.closePath();
                //flat end, round join, not at top or left
                context.lineJoin = ’round’;
                context.lineCap = ‘butt’;
                context.beginPath();
                context.moveTo(10, 100);
                context.lineTo(35, 100);
                context.lineTo(35, 125);
                context.stroke();
                context.closePath();
            }
        }
    </script>
</head>
<body>
    <div style=”position: absolute; top: 50px; left: 50px;”>
        <canvas id=”canvas” width=”500″ height=”500″>
            Your browser does not support the html 5 Canvas.
        </canvas>
    </div>
</body>
</html>

context.arc(x,y,radius,startAngle,ebdAngle,anticlockwise) //x,y圆形位置 raduis 圆半径 startAngle,ebdAngle,开始结束弧度值 Math,PI/180 anticlockwise false 顺时针 true 逆时针 定义弧线的方向

context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y); //

context.quadraticCurveTo(cpx,cpy,x,y);

html 代码

<!doctype html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title>Ch2Ex4 Arcs, Curves, and beziers</title>
    <script type=”text/javascript”>
        window.addEventListener(‘load’, eventWindowLoaded, false);
        function eventWindowLoaded() {
            canvasApp();
        }
        function canvasApp() {
            var theCanvas = document.getElementById(‘canvas’);
            if (!theCanvas || !theCanvas.getContext) {
                return;
            }
            var context = theCanvas.getContext(‘2d’);
            if (!context) {
                return;
            }
            drawScreen();
            function drawScreen() {
                //round end, bevel join, not at top or left of canvas
                context.beginPath();
                context.strokeStyle = “black”;
                context.lineWidth = 5;
                context.arc(100, 100, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false); // full circle
                context.moveTo(150, 0);
                context.bezierCurveTo(0, 125, 300, 175, 300, 300)
                context.stroke();
                context.closePath();
            }
        }
    </script>
</head>
<body>
    <div style=”position: absolute; top: 50px; left: 50px;”>
        <canvas id=”canvas” width=”500″ height=”500″>
            Your browser does not support the HTML 5 Canvas.
        </canvas>
    </div>
</body>
</html>

context.arcTo(x1,y1,x2,y2,r);
//x1 弧的起点的 x 坐标
y1 弧的起点的 y 坐标
x2 弧的终点的 x 坐标
y2 弧的终点的 y 坐标
r 弧的半径

html 代码

<!doctype html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title></title>
    <script type=”text/javascript”>
        window.onload = function () {
            var c = document.getElementById(“canvas”);
            var ctx = c.getContext(“2d”);
            ctx.beginPath();
            ctx.beginPath();
            ctx.moveTo(20, 20); // 创建开始点
            ctx.lineTo(100, 20); // 创建水平线
            ctx.arcTo(150, 20, 150, 101, 30); // 创建弧
            ctx.lineTo(150, 120); // 创建垂直线
            ctx.stroke(); // 进行绘制
        }
    </script>
</head>
<body>
    <div style=”position: absolute; top: 50px; left: 50px;”>
        <canvas id=”canvas” width=”500″ height=”500″>
            Your browser does not support the HTML 5 Canvas.
        </canvas>
    </div>
</body>
</html>

context.rect(x,y,width,height); 方法创建矩形。但它并不会真正将矩形画出,只能调用stroke() 或 fill()后才会真正作用于画布。

context.clip() //裁剪

html 代码

<!doctype html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title></title>
    <script type=”text/javascript”>
        window.onload = function () {
            var c = document.getElementById(“canvas”);
            var context = c.getContext(“2d”);
            context.fillStyle = “black”; //在屏幕上绘制一个大方框
            context.fillRect(10, 10, 200, 200);
            context.save();
            context.beginPath();
            //接切画布50*50
            context.rect(0, 0, 50, 50);
            context.clip();
            //红圈
            context.beginPath();
            context.strokeStyle = “red”; //需要颜色列表
            context.lineWidth = 5;
            context.arc(100, 100, 100, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false); // full circle
            context.stroke();
            context.closePath();
            context.restore();
            //再次剪切整个画布
            context.beginPath();
            context.rect(0, 0, 500, 500);
            context.clip();
            //画一个蓝色的圈
            context.beginPath();
            context.strokeStyle = “blue”;
            context.lineWidth = 5;
            context.arc(100, 100, 50, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false); // full circle
            context.stroke();
            context.closePath();
        }
    </script>
</head>
<body>
    <div style=”position: absolute; top: 50px; left: 50px;”>
        <canvas id=”canvas” width=”500″ height=”500″>
            Your browser does not support the HTML 5 Canvas.
        </canvas>
    </div>
</body>
</html>

drawImage(image, x, y)
drawImage(image, x, y, width, height)
drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight,destX, destY, destWidth, destHeight)//sourceX, sourceY 图像开始裁剪的左上角坐标 sourceWidth, sourceHeight,截取图片的宽高 destX, destY, 画布上的左上角X Y坐标 destWidth, destHeigh剪切的图片在画布上面的大小

context.save() //保存当前状态到堆栈

context. restore() //调出最后储存的堆栈恢复画布

html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title></title>
</head>
<body>
    <canvas id=”canvas” width=”500″ height=”300″></canvas>
    <script>
        var cav = document.getElementById(‘canvas’);
        var context = cav.getContext(‘2d’);
        context.fillStyle = “#ffffaa”;
        context.fillRect(0, 0, 500, 300);
        context.fillStyle = “#000”;
        context.font = “20px SimSun”;
        context.textBaseline = “top”;
        context.fillText(‘hello world’, 190, 80);
        //图片
        var img = new Image();
        img.src = ‘http://www.w3cfuns.com/uc_server/images/noavatar_big.gif’
        context.drawImage(img, 200, 200)
        //边框
        context.strokeStyle = “#000”;
        context.strokeRect(5, 5, 490, 290)
    </script>
</body>
</html>
猜字游戏

html 代码

<!doctype html>
<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title></title>
</head>
<body>
    <canvas id=”canvas” width=”500″ height=”300″></canvas>
    <form>
        <input type=”button” id=”createImageData” value=”Export Canvas Image”>
    </form>
    <script>
        window.onload = function () {
            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;
            var cav = document.getElementById(‘canvas’);
            var context = cav.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);
                var formElement = document.getElementById(“createImageData”);
                formElement.addEventListener(‘click’, createImageDataPressed, false);
                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);
                        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 _san”;
                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(‘Guesses: ‘ + 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);
                }
            }
            function createImageDataPressed(e) {
                window.open(theCanvas.toDataURL(), “canavsImage”, “left=0,top=0,width=” + theCanvas.width + “,height=” + theCanvas.height + “,toolbar=0,resizable=0”);
            }
        }
    </script>
</body>
</html>
web前端和后台开发
前端,后台开发必备技能
前端开发累还是后台开发累
» 本文来自:前端开发者 » 《前端H5 canvas 常用API(-)》
» 本文链接地址:https://www.rokub.com/6242.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!