美文网首页
canvas api

canvas api

作者: 小棋子js | 来源:发表于2021-03-23 13:46 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Document</title>
    <style>
        html, body {
            height: 100%;
        }
        body {
            margin: 0;
        }
    </style>
</head>
<body>
<canvas id="canvas"></canvas>

<script>
    // 获取画笔
    var ctx = canvas.getContext('2d'),
        body = {
            width: window.innerWidth,
            height: window.innerHeight
        };

    // 画布大小
    canvas.width = body.width;
    canvas.height = body.height;

    // 绘制步骤:
    // 1. 绘制路径: 开始路径, 直线/圆形/曲线路径, 按需闭合路径
    // 2. 绘制方式: fill(), stroke(), fillRect(x, y, w, h), strokeRect(x, y, w, h), fillText('text', x, y, maxLength), strokeText('text', x, y, maxLength)
    // 3. 样式和变形(作用全局, 向上覆盖): lineWidth(与lincap作用于stroke和strokeRect), lineCap, gradient, shadow, fillStyle/strokeStyle(颜色, 渐变), 文字样式(font, textAlign, textBaseLine等), 按需保存样式并对应恢复样式, 变换路径 (偏移, 旋转, 缩放), 擦除画布, 图像操作

    // 线宽, 默认1
    ctx.lineWidth = 2;

    // 线帽, round圆形/square矩形
    ctx.lineCap = 'round';

    // 线性渐变 (起点x, y, 终点x , y)
    var cl = ctx.createLinearGradient(0, 0, 200, 0);
    cl.addColorStop(0, '#F00');
    cl.addColorStop(.5, '#0F0');
    cl.addColorStop(1, '#00F');

    ctx.fillStyle = cl;
    ctx.fill();

    // 径向渐变(起点圆心x, y, 起点半径, 终点圆心x, y, 终点半径)
    var cr = ctx.createRadialGradient(100, 100, 0, 100, 100, 200);
    cr.addColorStop(0, '#FF0');
    cr.addColorStop(1, '#0FF');

    ctx.strokeStyle = cr;
    ctx.stroke();

    // 1. 直线
    ctx.beginPath();
    ctx.moveTo(0, 0); // 起点
    ctx.lineTo(100, 50); // 终点
    ctx.lineTo(200, 0);
    ctx.closePath(); // 闭合路径 (完成路径首尾闭合, 或用lineTo实现
    ctx.stroke();

    ctx.save(); // 将以下样式包括变形存入栈, 使样式只作用于save到restore之间
    // 阴影的偏移量x, y, 阴影颜色, 阴影模糊度
    ctx.shadowOffsetX = 30;
    ctx.shadowOffsetY = 0;
    ctx.shadowColor = '#F0F';
    ctx.shadowBlur = 5;

    // 2. 矩形
    ctx.strokeRect(0, 100, 200, 100);

    // 2. 圆形 (x, y, 半径, 起点路径角度(数值为3点钟位置开始, 顺或逆时针的点), 终点路径角度, 绘制方向(true为逆时针))
    ctx.beginPath();
    ctx.arc(100, 300, 50, Math.PI, Math.PI*3, false);
    ctx.stroke();
    ctx.restore(); // 从栈中取出样式

    // 3.1 二次元曲线 (控制点1, 终点)
    ctx.moveTo(200, 50); // 起点
    ctx.quadraticCurveTo(300, 0, 400, 50);

    // 3.2 贝塞尔曲线 (控制点1, 控制点2, 终点)
    ctx.moveTo(300, 100); // 起点
    ctx.bezierCurveTo(200, 200, 400, 200, 300, 300);
    ctx.stroke();

    // 文字样式
    ctx.font = 'bold 24px Microsoft Yahei';
    ctx.textAlign = 'center';
    ctx.textBaseLine = 'top';

    // ('文字', 位置x, y [, 最大文本宽(px)])
    ctx.fillText('文字1', 300, 350);
    ctx.strokeText('文字2', 300, 450, 180);

    var img = new Image();
    img.onload = function () {
        // 裁剪图像路径
        // ctx.arc(246, 46, 36, 0, Math.PI*2, true);

        // 调用裁剪方法
        // ctx.clip();

        // 图片透明度
        ctx.globalAlpha = .6;

        // 加载图像 (对象, 在源图像上裁剪坐标x, y, 宽, 高, 在画布上的显示坐标x, y, 宽, 高)
        ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, body.width, body.width * img.naturalHeight / img.naturalWidth);

        // 获取图像像素 (兼容问题只作获取图形像素)
        // var imgdata = ctx.getImageData(200, 0, img.width, img.height);

        // // 像素反显输出
        // for (var i = 0; i < imgdata.data.length; i += 4) {
        //  imgdata.data[i+0] = 255 - imgdata.data[i+0];
        //  imgdata.data[i+1] = 255 - imgdata.data[i+1];
        //  imgdata.data[i+2] = 255 - imgdata.data[i+2];
        //  imgdata.data[i+3] = 255;
        // }
        // ctx.putImageData(imgdata, 200, 100);

        // 图像的平铺方式
        // var cp = ctx.createPattern(img, 'repeat');
        // ctx.fillStyle = cp;
        // ctx.fillRect(200, 0, 200, 200);
    }
    // 指定图像路径
    img.src = '1.jpg';

    // 图形组合, 原有图形覆盖新图形, 默认新图形覆盖原有图形
    ctx.globalCompositeOperation = 'destination-over';

    // 将画布保存成图像
    // var i = id.toDataURL('image/png');
    // window.location = i;

    // 1. 移动
    // ctx.translate(10, 10);
    // 等价于
    // ctx.transform(1, 0, 0, 1, 10, 10)

    // 2. 缩放, 缩放图形坐标和大小
    // ctx.scale(1, 1);
    // 等价于
    // ctx.transform(1, 0, 0, 1, 0, 0);

    // 3. 旋转, 绕画布左上角
    ctx.save();
    // var r = 60*Math.PI/180;
    // ctx.rotate(r);
    ctx.rotate(toRad(60));
    ctx.fillRect(400, 100, 50, 50);
    ctx.restore();
    // 等价于:
    // ctx.transform(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0);

    // 设置角度的方法
    function toRad (rad) {
        return Math.PI * rad / 180;
    }

    // 擦除画布内容 (起点坐标x, y, 擦除区域宽, 高)
    ctx.clearRect(0, 70, 180, 30);

    // 查看原型结构
    console.log(ctx.constructor.prototype);
</script>
</body>
</html>

原点(0, 0)位于图像左上角,x轴的正向是原点向右,y轴的正向是原点向下。
使用 document.getElementById() 方法来为 <canvas> 元素得到DOM对象。一旦有了元素对象,你可以通过使用它的getContext() 方法来访问绘画上下文。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvasAPI绘制方法</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html,body{
            width: 100%;
            height: 100%;
            background-color: #fff;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200">
      您的浏览器不支持canvas!
    </canvas>
</body>
<script>
    var canvas = document.getElementById('myCanvas');
    //判断支持canvas
    if (canvas.getContext) {
      var ctx = canvas.getContext('2d');
    }
    // 绘制一条线
    ctx.beginPath(); // 开始路径绘制

    ctx.moveTo(20, 20); // 设置路径起点,坐标为(20,20)

    ctx.lineTo(200, 20); // 绘制一条到(200,20)的直线

    ctx.lineWidth = 1.0; // 设置线宽

    ctx.strokeStyle = "#ccc"; // 设置线的颜色

    ctx.stroke(); // 进行线的着色,这时整条线才变得可见

    //注意:生成路径的第一步叫做beginPath()。本质上,路径是由很多子路径构成,这些子路径都是在一个列表中,所有的子路径(线、弧形、等等)构成图形。而每次这个方法调用之后,列表清空重置,然后我们就可以重新绘制新的图形。

    // 矩形
    ctx.fillStyle = 'yellow';//设置矩形的填充色。
    ctx.fillRect(50, 50, 200, 100); //x,y,宽,高
    // 空心矩形
    ctx.strokeRect(10,10,200,100); //x,y,w,h
    // 清除矩形区域内容
    ctx.clearRect(100,50,50,50);  //x,y,w,h
    //绘制文本
    ctx.font = "Bold 20px Arial";   // 设置字体,字体、大小、样式
    ctx.textAlign = "left"; // 设置对齐方式
    ctx.fillStyle = "#008600";  // 设置填充颜色
    ctx.fillText("Hello!", 10, 50);     // 设置字体内容,以及在画布上的位置,string, x, y,
    ctx.strokeText("Hello!", 10, 100);  // 绘制空心字,string, x, y
    // 注意:fillText方法不支持文本断行,即所有文本出现在一行内。所以,如果要生成多行文本,只有调用多次fillText方法。
    //绘制圆形和扇形
    ctx.beginPath(); //生成路径的第一步叫做beginPath()
    ctx.arc(60, 60, 50, 0, Math.PI*2, true); //x,y,r半径,扇形的起始角度,终止角度,逆时针画(true)/顺时针画(false)
    //arcTo(x1, y1, x2, y2, radius)//根据给定的控制点和半径画一段圆弧,再以直线连接两个控制点。
    ctx.fillStyle = "#666"; // 设置填充颜色
    ctx.fill();//通过填充路径的内容区域生成实心的图形。
    //closePath();闭合路径之后图形绘制命令又重新指向到上下文中。
    //注意:当你调用fill()函数时,所有没有闭合的形状都会自动闭合,所以你不需要调用closePath()函数。但是调用stroke()时不会自动闭合。
    //注意:arc()函数中的角度单位是弧度,不是度数。角度与弧度的js表达式:radians=(Math.PI/180)*degrees。
    //设置渐变色
    //createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变
    var myGradient = ctx.createLinearGradient(0, 0, 0, 160); //参数是(x1, y1, x2, y2),其中x1和y1是起点坐标,x2和y2是终点坐标。通过不同的坐标值,可以生成从上至下、从左到右的渐变等等
    myGradient.addColorStop(0, "#BABABA"); 
    myGradient.addColorStop(1, "#000");
    ctx.fillStyle = myGradient;//颜色对象给矩形的填充色。
    ctx.fillRect(10,10,200,100);//矩形区域,x,y,宽,高
    //设置阴影
    ctx.shadowOffsetX = 10; // 设置水平位移
    ctx.shadowOffsetY = 10; // 设置垂直位移
    ctx.shadowBlur = 5; // 设置模糊度
    ctx.shadowColor = "rgba(0,0,0,0.5)"; // 设置阴影颜色
    ctx.fillStyle = "#CC0000"; 
    ctx.fillRect(10,10,200,100);
//绘制曲线quadraticCurveTo()
JavaScript 代码:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(188, 150);
context.quadraticCurveTo(288, 0, 388, 150);
context.lineWidth = 10;
// line color
context.strokeStyle = 'orange';
context.stroke();

quadraticCurveTo() 方法通过使用表示二次贝塞尔曲线的指定控制点,向当前路径添加一个点。
1. 开始点:moveTo(188,150)
2. 控制点:quadraticCurveTo(288, 0, 388, 150);
3. 结束点:quadraticCurveTo(288, 0, 388, 150)
</script>
</html>

相关文章

网友评论

      本文标题:canvas api

      本文链接:https://www.haomeiwen.com/subject/fxmbahtx.html