HTML5 canvas元素绘制三角形、矩形、圆形等基本图形

一、canvas元素

  • 目标:熟系绘制图形和图像
  • 属性:width height
  • API
<canvas width="800" height="600" id="MyCanvas"></canvas>
<script>
//获取 canvas 元素
var Mycanvas = document.getElementById('mc');
//获取 canvas 元素操作上下文 getContext 对象
var c = Mycanvas.getContext("2d");
</script>

二、canvas基本使用

  • 开始绘制:beginPath();
  • 结束绘制:closePath();//闭合路径
  • 清除画布:clearRect(x,y,width,height);
1. 绘制线段
	//线段
	mc.beginPath();//开始绘制
	mc.strokeStyle = 'red';//设置线段颜色
	mc.lineWidth = 3;//设置线段的粗细
	mc.moveTo(50,50);//开始点,设置x,y
	mc.lineTo(150,50);//途经点,设置x,y
	mc.stroke();//绘制

在这里插入图片描述

2. 绘制三角形
		//三角形
        mc.beginPath();//开始绘制
        mc.moveTo(200,50);//开始点,设置x,y
        mc.lineTo(200,150);//途经点,设置x,y
        mc.lineTo(250,100);
        // mc.lineTo(200,50);
        mc.closePath();//闭合路径
        mc.stroke();//绘制

在这里插入图片描述

3. 绘制矩形
		//矩形
        mc.beginPath();
        mc.fillStyle = "#ddffee";//设置实心颜色
        mc.strokeRect(50,97,100,50);//空心矩形,设置x,y,width,height
        mc.fillRect(50,150,100,50);//实心矩形,设置x,y,width,height

在这里插入图片描述

4. 绘制圆形
//圆形
        mc.beginPath();
        mc.strokeStyle = 'red';//设置线段颜色
        mc.fillStyle = "#ddffee";//设置实心颜色
        mc.arc(450,100,80,0*Math.PI/180,360*Math.PI/180,true);//设置x,y,r,begin,close,ture/false
        mc.stroke();//绘制空心圆
        mc.fill();//绘制实心圆

在这里插入图片描述

5. 文字动画
//绘制文字
        mc.beginPath();//开始绘制
        mc.fillStyle = "red";//实心颜色
        mc.font = "20px 微软雅黑";//设置文字样式
        var x = 0;
        function pmd(){
            x++;
            if(x>=1000){
                x = 0;
            }
            mc.clearRect(0,220,1000,100);//清除画布,设置清除区域x,y,w,h
            mc.fillText("我想带一人回云深不知处,带回去,藏起来",x,250);//设置str,x,y
            mc.fillText("你一开口我就想笑,我一笑,剑就拿不稳了",x+80,290);//设置str,x,y
        }
        setInterval("pmd()",10);//动画时间

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值