canvas使用

canvas使用(一)

      在html页面创建canvas标签,通过内联样式设置canvas宽高(不通过css样式设置,此种方式设置canvas里面会等比例缩放)
    <canvas id="myCanvas" width="400px" height="400px">如果浏览器不支持canvas,则会显示这里的细腻些</canvas>

canvas主要通过js进行绘制:
首先在js中获得canvas,通过getContext()获得2d对象

var drawing = document.getElementById("myCanvas");
var context = drawing.getContext("2d");

1.矩形的绘制

描边矩形:strokeRect(左上角x,左上角Y,宽,高)
				  strokeStyle 设置颜色
context.strokeStyle = "green";
context.strokeRect(30,30,100,100);
if(context){
   

    //描边绿矩形
    context.strokeStyle = "green";
    //左上角坐标为(30,30) 宽高分别为100,100
    context.strokeRect(30,30,100,100);

}

在这里插入图片描述
在这里插入图片描述

// 填充个红矩形:fillRect(左上角x,左上角Y,宽,高)
fillStyle 设置颜色
context.fillStyle = “red”;
context.fillRect(10,50,100,100);

if(context){
   
  
    // 填充个红矩形
    //设置矩形填充色为红色
    context.fillStyle = "red";
    //设置矩形左上角坐标(10,50) 宽高分别为100,100
    context.fillRect(10,50,100,100);

}

在这里插入图片描述
改变矩形填充色为黄色,矩形左上角坐标为(100,100)
在这里插入图片描述

//擦除矩形 clearRect(横坐标,纵坐标,宽,高) context.clearRect(0,0,400,400);

清楚全部canvas上图形

    // 填充个红矩形
    context.fillStyle = "green";
    context.fillRect(10,50,80,80);
  //擦除矩形
  context.clearRect(0,0,400,400);

清楚指定区域的图形

清楚从canvas上(0,0)坐标开始,宽高分别为20,100的矩形区域的图形:

    // 填充个红矩形
    context.fillStyle = "green";
    context.fillRect(10,50,80,80);
  //擦除矩形
  context.clearRect(0,0,40,100);

在这里插入图片描述

2.路径的绘制

// 设置落笔点:moveTo(横坐标x,纵坐标y)
设置路径:lineTo(横坐标x,纵坐标y)
设置颜色:strokeStyle
对路径进行绘制:stroke() 不适用该函数,canvas看不到上述绘制的路径

context.moveTo(50,50); context.lineTo(50,100);
context.strokeStyle = “red”; context.stroke();

  // 设置落笔点:moveTo(横坐标x,纵坐标y)
   context.moveTo(50,50);

  // 设置路径:lineTo(横坐标x,纵坐标y)
  context.lineTo(50,100);
  // 设置轨迹颜色:strokeStyle
  context.strokeStyle = "red";

  // 对路径进行绘制:stroke()  不适用该函数,canvas看不到上述绘制的路径
  context.stroke();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值