[前端] canvas绘制圆、渐变、字体和图片及其他

H5标签之canvas使用,前端学习必备。。

 

Canvas优缺点:
    依赖分辨率
    不支持事件处理器
    弱的文本渲染能力
    能够以 .png 或 .jpg 格式保存结果图像
    最适合图像密集型的游戏,其中的许多对象会被频繁重绘

 

实例使用

canvas标签:

 

<canvas id="canvas" width="600" height="350">您的浏览器不支持canvas</canvas>

 

 

 

一、绘制圆

1、空心圆:

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.arc(95,50,40,0,2*Math.PI); // arc(x,y,radius,开始弧度,结束弧度)
ctx.stroke();

 

 

2、实心圆

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.arc(95,50,40,0,2*Math.PI);  // arc(x,y,radius,开始弧度,结束弧度)
ctx.fillStyle = 'red';
ctx.fill();

 

 

 

二、绘制渐变

1、线性渐变

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var grd=ctx.createLinearGradient(0,0,200,0);  // createLinearGradient(x,y,x1,y1) 
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(0,0,180,80);

 

 

 

2、径向渐变

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var grd=ctx.createRadialGradient(75,50,5,90,60,100); // createRadialGradient(x,y,r,x1,y1,r1) 
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);

 

 

 

注:

addColorStop(0,'red');

addColorStop(1,'green');

这里的0,1表示起始到终点位置  中间可以插入 0.2 0.4 0.6 0.8等的位置

 

三、绘制字体

1、实心字体

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.font="30px Arial";
ctx.fillText("Hello World",10,50); // fillText(text,x,y)
 

 

 

2、空心字体

 

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.font="30px Arial";
ctx.strokeText("Hello World",10,50); // strokeText(text,x,y)

 

 

 

四、绘制图片

 

/*
 img       规定要使用的图像、画布或视频。
 sx            可选。开始剪切的 x 坐标位置。
 sy            可选。开始剪切的 y 坐标位置。
 swidth        可选。被剪切图像的宽度。
 sheight   可选。被剪切图像的高度。
 x         在画布上放置图像的 x 坐标位置。
 y         在画布上放置图像的 y 坐标位置。
 width     可选。要使用的图像的宽度。(伸展或缩小图像)
 height        可选。要使用的图像的高度。(伸展或缩小图像)
*/
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src='./image/zhaoliying.png';
img.onload = function() {  // 一定要在onload里绘制,否则图片绘制不出来 onload是加载完成事件
    ctx.drawImage(img, 0, 0, 300, 180, 10, 10, 300, 180);
}

 

欢迎关注技术开发分享录:http://fenxianglu.cn/

 

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值