用js实现canvas的绘制

canvas绘制

  1. 在html中嵌入<canvas></canvas>标签
  2. 使用js得到canvas引用  

canvas操作

  • 设置canvas的宽高 
var width = canvas.width = window.innerWidth; 

var height = canvas.height = window.innerHeight;

 

  •   得到可绘制的区域
var ctx = canvas.getContext('2d')

矩形

ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
ctx.fillRect(25, 100, 50, 50);


边框

ctx.strokeStyle = 'rgb(255, 255, 255)';//颜色
ctx.strokeRect(25, 25, 175, 200);//位置
ctx.lineWidth = 5;//线条宽度


绘制路径

beginPath() //调用这个函数  从笔所在位置开始绘制  
moveTo(x,y)//移动到另一个点  无路径
fill() //填充绘制的路径
stroke() 
lineTo(x,y)//移动到另一个点,有路径
arc(x,y,r,开始弧度,结束弧度,是否顺时针)
也可以使用 lineWidth and fillStyle/strokeStyle像前面一样


一个典型的绘制代码
 

ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.beginPath();
ctx.moveTo(50, 50);
// draw your path
ctx.fill();
function degToRad(degrees) {//角度转弧度
return degrees * Math.PI / 180;
};


文本绘制
 

fillText()
strokeText()//这两个函数都接受三个参数  要绘制的文本字符串,以及文本框左上角的X和Y坐标(实际上,是你绘制的文本框)。

例子:
ctx.strokeStyle = 'white'
ctx.lineHeight = 1
ctx.font = '36px airal'
ctx.strokeText('Canvas Text',50,50)

ctx.fillStyle = 'red'
ctx.font = '48px georgia'
ctx.fillText('Canvas Text',50,150)


在画布上绘制图像

drawImage()//接受9个参数  图片的位置  x、y代表起始位置  四五个参数代表图片的宽高  


循环和动画

translate(x,y)//移动 起始点(坐标轴中心)到某个点

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值