HTML5 Canvas专题

本文详细介绍了HTML5 Canvas的各个关键特性,包括路径方法、线条样式、矩形、圆弧绘制,以及贝塞尔曲线的使用。此外,还涵盖了剪切路径、状态保存和恢复、阴影、渐变和填充等高级特性,对文本处理、坐标转换、图形合成和图像绘制做了深入探讨,是HTML5 Canvas学习的重要参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

canvas参考手册

路径方法

  • beginPath():开启一条路径,或重置当前路径
  • closePath():创建从当前点回到起始点的路径
  • stroke():绘制当前路径
  • fill():填充当前路径
  • moveTo():把路径移动到画布中的指定点,不创建线条
  • lineTo():添加一个新点,然后创建从该点到画布中最后指定点的线条(该方法并不会创建线条)

线条样式

  • lineCap:设置或返回线条的结束端点样式
    1、butt:默认,向线条的每个末端添加平直的边缘
    2、round:向线条的每个末端添加圆形线帽
    3、square:向线条的每个末端添加正方形线帽
    4、“round”和“square”会使线条略微变长,因为加上了线帽
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>线条样式</title>
</head>
<body>
	<!-- 创建画布 -->
    <canvas id="canvas02" width="500px" height="200px" style="background: #a9a9a9";>
        您的浏览器不支持canvas标签
    </canvas>
    <script>
        // 线帽(结束端点)
        var myCanvas2 = document.getElementById("canvas02");//获取画布对象
        var myContext2 = myCanvas2.getContext("2d");//设置画布绘图环境
        myContext2.lineWidth = 20;// 设置线宽
        myContext2.strokeStyle = "orange";//设置线的颜色
        myContext2.lineCap = "butt"; //默认线帽
        myContext2.moveTo(90, 50);//设置线条起点
        myContext2.lineTo(400, 50);//设置新的节点
        myContext2.stroke();//绘制线条

        myContext2.beginPath();//开始新的线段
        myContext2.lineCap = "round";
        myContext2.strokeStyle = "red";
        myContext2.moveTo(90, 100);
        myContext2.lineTo(400, 100);
        myContext2.stroke();

        myContext2.beginPath();//开始新的线段
        myContext2.lineCap = "square";
        myContext2.strokeStyle = "blue";
        myContext2.moveTo(90, 150);
        myContext2.lineTo(400, 150);
        myContext2.stroke();
    </script>
</body>
</html>
  • lineJoin:设置或返回两条线相交时,所创建的拐角类型
    1、miter:默认,创建尖叫
    2、bevel:创建斜角
    3、round:创建圆角
    <canvas id="canvas03" width="500px" height="200px" style="background: #a9a9a9";>
        您的浏览器不支持canvas标签
    </canvas>
    <script>
        // 拐角类型
        var myCanvas3 = document.getElementById("canvas03");
        var cxt3 = myCanvas3.getContext("2d");//设置画布绘图环境
        cxt3.lineWidth = 20;// 设置线宽
        cxt3.strokeStyle = "orange";//设置线的颜色
        cxt3.lineJoin = "miter";//默认
        cxt3.lineJoin = "round";//圆角
        cxt3.lineJoin = "bevel";//斜角
        cxt3.moveTo(100, 50);
        cxt3.lineTo(400, 50);
        cxt3.lineTo(400, 150);
        cxt3.closePath();
        cxt3.stroke();
    </script>
  • miterLimit:设置或返回最大斜接长度
    斜接长度指的是在两条线交汇处内角和外角之间的距离。该属性定义了斜连线长度和线条宽度的最大比率
    1、只有lineJoin属性为miter
    时,miterLimit才有效
    2、边角的角度越小,斜接长度就会越大。为了避免斜接长度过长,我们可以使用miterLimit属性
    3、如果斜接长度超过miterLimit的值,边角会以lineJoin的“bevel”类型来显示

矩形

  • rect(x, y, w, h):创建矩形
  • fillRect(x, y, w, h):绘制填充矩形
  • strokeRect(x, y, w, h):绘制无填充矩形
  • clearRect(x, y, w, h):在给定的矩形内清除指定的像素
   <canvas id="canvas05" width="500px" height="200px" style="background: #a9a9a9";>
       您的浏览器不支持canvas标签
   </canvas>
   <button onclick="clearCanvas()">清空画布</button>
   <script>
       // 绘制矩形和清空画布
       var myCanvas5 = document.getElementById("canvas05");
       var cxt5 = myCanvas5.getContext("2d");//设置画布绘图环境
       cxt5.lineWidth = 10;// 设置线宽
       cxt5.fillStyle = "red";//填充样色
       cxt5.strokeStyle = "blue";//描边颜色

       cxt5.strokeRect(50, 50, 100, 100);//绘制无填充矩形
       cxt5.fillRect(70, 70, 60, 60);//绘制填充矩形

       // cxt5.clearRect(80, 80, 30, 30);//清除画布
       function clearCanvas(){
           cxt5.clearRect(0, 0, 500, 200);
       }
   </script>

圆、圆弧

arc:创建圆、弧、曲线

  • arc():创建弧、曲线(用于创建圆形或部分圆)
    <canvas id="canvas06" width="300px" height="600px" style="background: #a9a9a9";>
        您的浏览器不支持canvas标签
    </canvas>
    <script>
        // 绘制圆和圆弧
        var myCanvas6 = document.getElementById("canvas06");
        var cxt6 = myCanvas6.getContext("2d");//设置画布绘图环境
        cxt6.lineWidth = 10;// 设置线宽
        cxt6.fillStyle = "red";//填充样色
        cxt6.strokeStyle = "black";//描边颜色

        //描边圆、空心圆
        cxt6.beginPath();
        cxt6.arc(50, 50, 30, 0, Math.PI*3);
        cxt6.stroke();

        //填充圆
        cxt6.beginPath();
        cxt6.arc(150, 50, 30, 0, Math.PI*2);
        cxt6.fill();

        //同时带有描边和填充的圆
        cxt6.beginPath();
        cxt6.arc(250, 50, 30, 0, Math.PI*2);
        cxt6.fill();
        cxt6.stroke();

        //描边、填充和同时描边与填充的弧线
        //默认值为false:顺时针
        cxt6.beginPath();
        cxt6.arc(50, 150, 30, 0, Math.PI*2/3);
        cxt6.stroke();

        cxt6.beginPath();
        cxt6.arc(150, 150, 30, 0, Math.PI*2/3);
        cxt6.fill();

        cxt6.beginPath();
        cxt6.arc(250, 150, 30, 0, Math.PI*2/3);
        cxt6.fill();
        cxt6.stroke();

        //描边、填充和同时描边与填充的弧线
        //true:逆时针
        cxt6.beginPath();
        cxt6.arc(50, 250, 30, 0, Math.PI*2/3, true);
        cxt6.stroke();

        cxt6.beginPath();
        cxt6.arc(150, 250, 30, 0, Math.PI*2/3, true);
        cxt6.fill();

        cxt6.beginPath();
        cxt6.arc(250, 250, 30, 0, Math.PI*2/3, true);
        cxt6.fill();
        cxt6.stroke();

        //描边、填充和同时描边与填充的弧线
        //true:逆时针
        //封闭路径
        cxt6.beginPath();
        cxt6.arc(50, 350, 30, 0, Math.PI*2/3, true);
        cxt6.closePath();
        cxt6.stroke();

        cxt6.beginPath();
        cxt6.arc(150, 350, 30, 0, Math.PI*2/3, true);
        cxt6.closePath();
        cxt6.fill();

        cxt6.beginPath();
        cxt6.arc(250, 350, 30, 0, Math.PI*2/3, true);
        cxt6.closePath();
        cxt6.fill();
        cxt6.stroke();
    </script>

arcTo:创建弧、曲线

  • arcTo(x1, y1, x2, y2, r):创建两切线之间的弧、曲线
    <!-- ================绘制圆角矩形================================== -->
    <canvas id="canvas07" width="300px" height="300px" style="background: #a9a9a9";>
        您的浏览器不支持canvas标签
    </canvas>
    <script>
        // 绘制圆角矩形 
        var myCanvas7 = document.getElementById("canvas07");
        var cxt7 = myCanvas7.getContext("2d");//设置画布绘图环境
        cxt7.lineWidth = 5;// 设置线宽
        cxt7.fillStyle = "red";//填充样色
        cxt7.strokeStyle = "black";//描边颜色

        // cxt7.beginPath();
        // cxt7.moveTo(20, 30);//起点
        // cxt7.arcTo(20, 20, 280, 20, 10);
        // cxt7.arcTo(280, 20, 280, 280, 10);
        // cxt7.arcTo(280, 280, 20, 280, 10);
        // cxt7.arcTo(20, 280, 20, 20, 10);
        // cxt7.closePath();
        // cxt7.stroke();
        // cxt7.fill();

        //封装绘制圆角矩形的函数
        function roundRect(x, y, w, h, r){
            cxt7.beginPath();
            cxt7.moveTo(x, y+r);//起点
            cxt7.arcTo(x, y, x+w, y, r);
            cxt7.arcTo(x+w, y, x+w, y+h, r);
            cxt7.arcTo(x+w, y+h, x, y+h, r);
            cxt7.arcTo(x, y+h, x, y, r);
            cxt7.closePath();
            cxt7.stroke();
            cxt7.fill();
        }

        roundRect(20, 20, 260, 260, 10);
    </script>

贝塞尔曲线

贝塞尔曲线可以绘制任何曲线,包括直线

  • quadraticCurveTo(cx, cy, x, y):创建二次方贝塞尔曲线
    1、二次方贝塞尔曲线需要两个点。第一个点是用于二次方贝塞尔计算中的控制点,第二个是曲线的结束点。曲线的开始点是当前路径中最后一个点。如果路径不存在,那么请使用beginPath和moveTo方法来定义开始点

  • bezierCurveTo():创建三次方贝塞尔曲线
    1、三次方贝塞尔曲线需要三个点。前两个点为控制点,第三个点为结束点。曲线的开始点是当前路径中最后一个点。如果路径不存在,那么请使用beginPath和moveTo方法来定义开始点

    <canvas id="canvas" width="500px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var cxt = c.getContext("2d");
        cxt.lineWidth = 2;
        cxt.fillStyle = "red";
        cxt.strokeStyle = "black";
        //二次方贝塞尔曲线
        cxt.beginPath();
        cxt.moveTo(50, 50);
        cxt.quadraticCurveTo(150, 200, 300, 50);
        cxt.stroke();

        //三次方贝塞尔曲线
        cxt.beginPath();
        cxt.strokeStyle = "red";
        cxt.moveTo(50, 150);
        cxt.bezierCurveTo(400, 10, 30, 250, 450, 70);
        cxt.stroke();
    </script>

剪切路径

  • clip():从原始画布剪切任意形状和尺寸的区域
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>裁切路径</title>
    <style type="text/css">
        img{
            position: absolute;
            clip: rect(150px, 500px, 600px, 200px);
        }
    </style>
</head>
<body>
    <!-- <img src="../imgs/timg.jfif" alt="这是一张图片" title="嘿嘿嘿"> -->
    <canvas id="canvas" width="500px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        ctx.lineWidth = 2;
        ctx.fillStyle = "red";
        ctx.strokeStyle = "black";
        ctx.rect(50, 20, 200, 200);
        ctx.stroke();
        ctx.clip();

        ctx.beginPath();
        ctx.rect(0, 0, 100, 60);
        ctx.rect(300, 250, 100, 100);
        ctx.fill();
    </script>
</body>
</html>
  • isPointInPath():如果指定的点位于当前路径中,则返回true,否则返回false
    <canvas id="canvas" width="500px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        ctx.lineWidth = 5;
        ctx.fillStyle = "red";
        ctx.strokeStyle = "black";
        ctx.rect(20, 20, 200, 200);
        ctx.stroke();
        ctx.fill();

        if(ctx.isPointInPath(50, 50)){
            alert("该点在当前路径中");
        }else{
            alert("该店不在当前路径中");
        };
    </script>

状态的保存和恢复

  • save():保存当前环境的状态
  • restore():返回之前保存过的路径状态和属性
    注:1、可以多次保存,逐级恢复;最后保存的最先还原;restore总是还原离他最近的save点(已经还原的不能第2次还原)
    2、绘图属性是可以保存和恢复的,但绘制的内容可不是,也就是说你恢复了绘图环境(状态),并不会恢复其所绘制的图形
    <canvas id="canvas" width="800px" height="300px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        ctx.lineWidth = 5;
        ctx.fillStyle = "red";
        ctx.strokeStyle = "black";
        ctx.rect(20, 20, 100, 100);
        ctx.stroke();
        ctx.fill();
        //保存当前的绘图状态
        ctx.save();

        //绘制另外一个图形
        ctx.beginPath();
        ctx.lineWidth = 15;
        ctx.fillStyle = "black";
        ctx.strokeStyle = "red";
        // ctx.save();

        ctx.restore();//恢复状态
        ctx.arc(250, 75, 50, 0, Math.PI*2);
        ctx.stroke();
        ctx.fill();      
    </script>

阴影、渐变、填充

  • fillStyle:设置或返回用于填充绘画的颜色、渐变或填充模式
  • strokeStyle:设置或返回用于笔触的颜色、渐变模式

阴影

1、shadowColor:设置或返回用于阴影的颜色
2、shadowBlur:设置或范湖用于阴影的模糊级别,越大越模糊
3、shadowOffsetX:设置或返回阴影距形状的水平距离
4、shadowOffsetY:设置或返回阴影距形状的垂直距离

    <canvas id="canvas" width="500px" height="300px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        ctx.fillStyle = "orange";
        ctx.shadowColor = "red";
        ctx.shadowOffsetX = 30;
        ctx.shadowOffsetY = 10;
        ctx.shadowBlur = 9;
        ctx.fillRect(50, 50, 100, 100);
    </script>

渐变

  • createLinearGradient(x0, y0, x1, y1):创建线性渐变(用在画布内容上,两个点代表线性渐变的方向)
  • createRadialGradient(x0, y0, r0, x1, y1, r1):创建放射状、环形的渐变(用在画布内容上)
  • addColorStop():规定渐变对象中的颜色和停止位置
    <canvas id="canvas" width="500px" height="300px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        // var jianbian = ctx.createLinearGradient(0, 0, c.width, c.height);
        var jianbian2 = ctx.createRadialGradient(c.width/2, c.height/2, 10, c.width/2, c.height/2, 200);

            jianbian2.addColorStop(0, "blue");
            jianbian2.addColorStop(0.25, "white");
            jianbian2.addColorStop(0.5, "red");
            jianbian2.addColorStop(0.75, "yellow");
            jianbian2.addColorStop(1, "green");

            ctx.fillStyle = jianbian2;
            ctx.fillRect(0, 0, c.width, c.height);
    </script>

填充

  • createPattern(image, “repeat | repeat-x | repeat-y | no-repeat”):在指定的方向上重复指定的元素
    1、元素可以是图片、视频或者其他canvas元素
    2、被重复的元素可用于绘制、填充矩形、圆形或线条等等
    注:如果createPattern()方法的image参数值不是当前页面一个已经存在的image对象或canvas对象,那么我们需要等待浏览器将图片加载完毕后才能调用createPattern方法及后续操作,否则将无法正确显示对应的图形
    <!-- 重复元素 -->
    <canvas id="canvas" width="800px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
            ctx.fillStyle = "red";

        // 创建一个表示图片的Image对象
        var img = new Image();
        img.src = "../imgs/timg.jfif";
        img.onload = function(){
            // 创建CanvasPattern对象,指定上述图片进行水平的重复平铺
            var pattern = ctx.createPattern(img, "repeat-x");
            ctx.fillStyle = pattern;
            ctx.fillRect(0, 0, 800, 500);
        }     
    </script>

文本

属性

  • font:设置或返回文本内容的当前字体属性
  • textAlign:设置或返回文本内容的水平对齐方式
    1、start:默认。文本在指定的位置开始
    2、end:文本在指定的位置结束
    3、center:文本的中心被放置在指定的位置
    4、left:文本左对齐
    5、right:文本右对齐
    <canvas id="canvas" width="800px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
            ctx.lineWidth = 5;
            ctx.fillStyle = "red";
            ctx.strokeStyle = "black";
            ctx.font = "20px 隶书";

            ctx.beginPath();
            ctx.moveTo(300, 0);
            ctx.lineTo(300, c.height);
            ctx.stroke();

            ctx.beginPath();
            ctx.textAlign = "start";
            ctx.fillText("HTML的Canvas标签", 300, 50);

            ctx.beginPath();
            ctx.textAlign = "end";
            ctx.fillText("HTML的Canvas标签", 300, 100);

            ctx.beginPath();
            ctx.textAlign = "center";
            ctx.fillText("HTML的Canvas标签", 300, 150);
   
            ctx.beginPath();
            ctx.textAlign = "left";
            ctx.fillText("HTML的Canvas标签", 300, 200);

            ctx.beginPath();
            ctx.textAlign = "right";
            ctx.fillText("HTML的Canvas标签", 300, 250);
    </script>
  • textBaseline:设置或返回在绘制文本时使用的当前文本基线(垂直对齐方式)
    1、top:文本基线是em方框的顶端
    2、bottom:文本基线是em方框的低端
    3、middle:文本基线是em方框的正中
    4、alphabetic:默认方式。文本基线是普通的字母基线
    5、ideographic:文本基线是表意基线。一般用于绘制中文或日文字符串
    6、hanging:文本基线是悬挂基线。一般用于绘制印度语字符串
  // 基线对齐
  ctx.beginPath();
  ctx.strokeStyle = "blue";
  ctx.moveTo(0, 150);
  ctx.lineTo(1000, 150);
  ctx.stroke();

  ctx.beginPath();
  ctx.font = "30px 宋体";
  ctx.textBaseline = "top";
  ctx.fillText("top顶", 50, 150);
  ctx.textBaseline = "bottom";
  ctx.fillText("bottom底", 130, 150);
  ctx.textBaseline = "middle";
  ctx.fillText("middle中", 250, 150);
  ctx.textBaseline = "alphabetic";
  ctx.fillText("alphabetic", 400, 150);
  ctx.textBaseline = "ideoprahic";
  ctx.fillText("ideoprahic", 570, 150);
  ctx.textBaseline = "hanging";
  ctx.fillText("hanging", 750, 150);

方法

  • fillText():在画布上绘制填充的文本
  • strokeText():在画布上绘制无填充的文本
  • measureText():返回包含指定文本宽度的对象
    1、语法:context.measureText(text).width
   ctx.beginPath();
   ctx.fillStyle = "black";
   ctx.strokeStyle = "red";
   ctx.font = "60px 楷体";
   var str = "HHH";
   var fontWidth = ctx.measureText(str).width;

   ctx.fillText(str, 200, 100);
   ctx.moveTo(200, 100);
   ctx.lineTo(290, 100);
   ctx.fillText("str的宽度为" + fontWidth, 200, 200);
   ctx.stroke();   

坐标转换

  • translate():重新映射画布上的(0, 0)位置(即移动坐标原点)
  • scale():缩放当前绘图至更大或更小
    注:如果对绘图进行缩放,所有之后的绘图也会被缩放。定位也会被缩放。如果你scale(2, 2),那么绘图将定位于距离画布左上角两倍远的位置
  • rotate():旋转当前绘图
    注:参数单位为弧度。如需将角度转换为弧度,请使用degrees*Math.PI/180公式计算。再次转换时会叠加效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>坐标转换</title>
</head>
<body>
    <canvas id="canvas" width="1000px" height="500px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
            ctx.lineWidth = 5;
            ctx.fillStyle = "blue";
            ctx.strokeStyle = "red";
            ctx.font = "30px 宋体";
            
            ctx.moveTo(0, 0);
            ctx.lineTo(500, 0);
            ctx.moveTo(0, 0);
            ctx.lineTo(0, 300);
            ctx.stroke();

            ctx.strokeRect(20, 20, 50, 50);
            ctx.fillText("坐标转换", 85, 70);

            //坐标平移、缩放、旋转
            ctx.translate(100, 100);
            ctx.scale(2, 2);
            ctx.rotate(15*Math.PI/180);


            ctx.moveTo(0, 0);
            ctx.lineTo(500, 0);
            ctx.moveTo(0, 0);
            ctx.lineTo(0, 300);
            ctx.stroke();

            ctx.strokeRect(20, 20, 50, 50);
            ctx.fillText("坐标转换", 85, 70);   
    </script>
</body>
</html>

图形合成

源图像 = 您打算放置到画布上的绘图。

目标图像 = 您已经放置在画布上的绘图

  • globalAlpha:设置或返回绘图的当前alpha或透明值。设置透明度后,其后的所有绘制的透明度都被改变,直到下次重置该属性
  • globalCompositeOperation:设置或返回新图像如何绘制到已有的图像上
    1、source-over:默认。在目标图像上显示源图像
    2、source-atop:在目标图像顶部显示源图像。源图像位于目标图像之外的部分是不可见的
    3、source-in:在目标图像中显示源图像。只有目标图像内的源图像部分会显示,目标图像是透明的
    4、source-out:在目标图像之外显示源图像。只会显示目标图像之外源图像部分,目标图像是透明的
    5、destination-over:在源图像上方显示目标图像
    6、destination-atop:在源图像顶部显示目标图像。源图像之外的目标图像部分不会被显示
    7、destination-in:在源图像中目标图像。只有源图像内的目标图像部分会被显示,源图像是透明的
    8、destination-out:在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的
    9、lighter:显示源图像+目标图像。这个值与顺序无关,如果源与目标重叠,就将两者的颜色相加。得到的颜色值最大取值为255,结果就为白色
    10、copy:显示源图像。忽略目标图像。这个值与顺序无关,只绘制源,覆盖掉目标
    11、xor:使用异或操作对源图像与目标图像进行组合。这个值与顺序无关,只绘制出不重叠的源与目标区域。所有重叠的部分都变成透明的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>合成</title>
    <style type="text/css">
        input{
            background: orange;
            width: 100px;
            height: 100px;
            border-radius: 100px;
            position: absolute;
            left: 665px;
            top: 200px;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="300px" height="300px" style="background: #a9a9a9";>
        你的浏览器暂不支持canvas标签
    </canvas>
    <!-- <input type="button" value="合成" οnclick="gco()"> -->
    <select id="hc" size="11" onclick="gco()">
        <option value="source-over" selected>source-over</option>
        <option value="source-atop">source-atop</option>
        <option value="source-in">source-in</option>
        <option value="source-out">source-out</option>
        <option value="destination-over">destination-over</option>
        <option value="destination-atop">destination-atop</option>
        <option value="destination-in">destination-in</option>
        <option value="destination-out">destination-out</option>
        <option value="lighter">lighter</option>
        <option value="copy">copy</option>
        <option value="xor">xor</option>
    </select>
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var selectElement = document.getElementById("hc");
            ctx.font = "20px 隶书";
        function gco(){
            // alert(selectElement.value);
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.save();
            ctx.fillStyle = "red";
            ctx.fillRect(50, 50, 100, 100);
            ctx.fillText("目标图像", 50, 45);
            ctx.globalCompositeOperation = selectElement.value;
            ctx.beginPath();
            ctx.fillStyle = "blue";
            ctx.arc(150, 150, 50, 0, Math.PI*2);
            ctx.fillText("源图像", 150, 225);
            ctx.fill();
            ctx.restore();
        }
    </script>
</body>
</html>

图像绘制

  • drawImage(img, sx, sy, swidth, sheight, width, height):向画布上绘制图像、画布或视频
    1、img:规定要使用的图像、画布或视频
    2、sx:可选。开始剪切的x坐标位置
    3、sy:可选。开始剪切的y坐标位置
    4、swidth:可选。被剪切图像的宽度
    5、sheight:可选。被剪切图像的高度
    6、x:在画布上放置图像的x坐标位置
    7、y:在画布上放置图像的y坐标位置
    8、width:可选。要使用的图像的宽度(伸展或缩小图像)
    9、height:可选。要使用的图像的高度(伸展或缩小图像)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图像的绘制</title>
</head>
<body>
    <canvas id="canvas" width="1000" height="1000" style="background: #a0a0a0;">
        你的浏览器暂不支持canvas标签
    </canvas>
    <img id="tp" src="../imgs/timg.jfif" alt="">
    <script>
        var c = document.getElementById("canvas");
        var cxt = c.getContext("2d");
        var img = document.getElementById("tp");
            //在图像未被加载之前不能对其绘制
            img.onload = function(){
                cxt.drawImage(img, 300, 400, 300, 300, 10, 10, 500, 500);
            }
    </script>

    <input id="inp" type="range" value="1" min="1" max="30">
    <script>
        var c = document.getElementById("canvas");
        var cxt = c.getContext("2d");
        var scaler = document.getElementById("inp");
        var scale = 0.5;
        
        var img = new Image();
            img.src = "../imgs/timg.jfif";
            //在图像未被加载之前不能对其绘制
        function draw(){
                    TuKuan = c.width*scale;//图像的宽
                    TuGao = c.height*scale;
                    x = c.width/2 - TuKuan/2;//图像的位置
                    y = c.height/2- TuGao/2;
                    cxt.clearRect(0, 0, c.width, c.height);//清空上一次绘图
                    cxt.drawImage(img, x, y, TuKuan, TuGao);
        }
        img.onload = draw;
        scaler.onchange = function(e){
                    scale = e.target.value/10;//获取事件标签,然后再获取标签的值
                    // alert(scale);
                    draw();
                }
        
    </script>
</body>
</html>

像素操作

属性

  • width:返回ImageData对象的宽度(可以理解为一行像素的个数)
  • height:返回ImageData对象的高度(可以理解为一列像素的个数)
  • data:返回一个数组对象,其包含指定的ImageData对象的图像数据
    1、该对象包含每一个像素的四个rgba值,注意每个值都在0-255之间
    2、这四个参数和CSS中讲的rgba颜色表示法原理相同,四个参数分别表示红、绿、蓝以及透明度
    3、所不同的是这里的透明度取值也是0-255,255表示完全不透明,0表示完全透明

方法

  • getImageData(x, y, w, h):返回ImageData对象,该对象为画布上指定的矩形复制像素数据
  • putImageData(imgData, x, y, dirtyX, dirtyY, w, h):把图像数据(从指定的ImageData对象)放回画布上
    1、imgData:规定要放回画布的ImageData对象
    2、x/y:要放回的位置坐标,ImageData对象左上角,以像素计算
    3、dirtyX,dirtyY,w,h:可选。对已放回画布的图像进行截取,前两个为图像的起点,后者为在画布上绘制图像所使用的宽度、高度
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>像素的操作</title>
</head>
<body>
    <input type="button" value="像素操作" onclick="putImage()">
    <input type="button" value="反色绘制" onclick="fs()">
    <input type="button" value="滤镜效果" onclick="lj()">
    <canvas id="canvas" width="850" height="400" style="background: #a0a0a0;">
        你的浏览器暂不支持canvas标签
    </canvas>
   
    <script>
        // var c = document.getElementById("canvas");
        // var cxt = c.getContext("2d");
        // cxt.fillStyle = "rgba(255, 10, 11, 0.5)";
        // cxt.fillRect(0, 0, 100, 100);  

        // var XS = cxt.getImageData(0, 0, 100, 100);
        // alert(XS.width);
        // alert(XS.height);
        // alert(XS.data.length);
        // alert(XS.data);
        // alert(XS.data[0]);
        // alert(XS.data[1]);
        // alert(XS.data[2]);
        // alert(XS.data[3]);
        // alert(XS.data[4]);

        // cxt.putImageData(XS, 110, 0);
        // cxt.putImageData(XS, 110, 0);
        // cxt.putImageData(XS, 110, 0, 0, 0, 50, 50);
        // cxt.putImageData(XS, 110, 0, 50, 0, 100, 50);
        // cxt.putImageData(XS, 110, 0, 0, 50, 50, 50);
        // cxt.putImageData(XS, 110, 0, 50, 50, 50, 50);
    </script>

    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var img = new Image();
        img.src = "../imgs/timg.jfif";
        img.onload = function(){
            ctx.drawImage(img, 0, 0, 400, 400);
        }
        //像素操作
        function putImage(){
            // 用getImageData从画布上获取像素
            var imageData = ctx.getImageData(0, 0, 400, 400);
            //将获取的整个像素数据画到canvas画布上
            ctx.putImageData(imageData, 450, 0);
        }
        //反色绘制
        function fs(){
            ctx.clearRect(450, 0, 400, 400);
            var imageData = ctx.getImageData(0, 0, 400, 400);
            for (var i = 0; i < imageData.data.length; i+=4){
                imageData.data[i+0] = 255-imageData.data[i+0];
                imageData.data[i+1] = 255-imageData.data[i+1];
                imageData.data[i+2] = 255-imageData.data[i+2];
            }
            ctx.putImageData(imageData, 450, 0);
        }
        //滤镜效果
        function lj(){
            ctx.clearRect(450, 0, 400, 400);
            var imageData = ctx.getImageData(0, 0, 400, 400);
            for (var i = 0; i < imageData.data.length; i+=4){
                imageData.data[i+0] = 255;
                // imageData.data[i+1] = 0;
                // imageData.data[i+2] = 255;
            }
            ctx.putImageData(imageData, 450, 0);
        }
    </script>
</body>
</html>
  • createImageData():创建新的、空白的ImageData对象
    1、var imgData = context.createImageData(width, height):以指定的尺寸(像素)创建新的ImageData对象
    2、var imgData = context.createImageData(imageData):创建与指定的另一个ImageData对象尺寸相同的新ImageData对象(但不会赋值图像数据)
    <script>
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var imageData = ctx.createImageData(400, 400);
        for (var i = 0; i < imageData.data.length; i += 4){
            imageData.data[i + 0] = 0;
            imageData.data[i + 1] = 0;
            imageData.data[i + 2] = 0;
            imageData.data[i + 3] = 255;
            
        }
        ctx.putImageData(imageData, 0, 0);
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值