HTML5 Canvas CanvasRenderingContext2D 属性详细解读

本文深入探讨了HTML5 Canvas API中的CanvasRenderingContext2D属性,包括fillStyle、strokeStyle、font、globalAlpha等关键属性的用法,并通过示例展示了如何设置颜色、阴影效果以及文本对齐方式等,帮助读者更好地理解和使用Canvas进行图形绘制。
摘要由CSDN通过智能技术生成

HTML5 Canvas API 之 CanvasRenderingContext2D

文档地址 Canvas API CanvasRenderingContext2D

1.属性

  • canvas 对与给定上下文关联的HTMLCanvasElement对象的只读引用

    <canvas id="canvas"></canvas>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    ctx.canvas; // <canvas id="canvas"></canvas>
    
  • fillStyle 描述颜色和样式的属性 color | gradient | pattern

  • strokeStyle 画笔(绘制图形)颜色。默认 balck || #000

    // color
    ctx.fillStyle = "#333333";
    ctx.fillStyle = "red"; 
    ctx.fillStyle = "rgb(0, 0, 0)";
    ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
    // gradient
    var grd = ctx.createLinearGradient(0, 0, 80, 0); // 设置线性渐变规则
    grd.addColorStop(0, "black");
    grd.addColorStop(0.5, "white");
    grd.addColorStop(1, "black"); // 渐变范围 0 - 1
    ctx.fillStyle = grd;
    ctx.fillRect(10, 10, 100, 100);
    

    ctx.createLinearGradient(0, 80, 80, 0)3
    ctx.createLinearGradient(0, 0, 80, 80)2
    ctx.createLinearGradient(0, 0, 80, 0)1

    // pattern 元素可以是图片、视频,或者其他 <canvas> 元素
    var img = new Image();
    img.src = "img/test2.jpg";
    img.onload = function(){
         
        var pat = ctx.createPattern(img, "repeat"); // repeat|repeat-x|repeat-y|no-repeat
        ctx.lineWidth = 30;
        ctx.strokeStyle = pat;
        ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);
        ctx.stroke();
        ctx.closePath();
        // ctx.fillStyle = pat;
        // ctx.fillRect(0, 0, 100, 100);
        // ctx.fill();
    }
    

    ctx.arc(100, 100, 80, 0, 2 * Math.PI, false);在这里插入图片描述
    ctx.fillRect(0, 0, 100, 100);在这里插入图片描述

  • font 符合CSS font 语法的DOMString 字符串。默认字体是 10px sans-serif。

    ctx.font = "bold 48px serif";
    ctx.strokeText("Hello world", 50, 100);
    // 加载自定义字体
    var fot = new FontFace('testFont', 'url(x)');
    fot.load().then(function() {
         
      ctx.font = "14px testFont";
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值