您的位置:首页 > 其它

canvas绘制圆、渐变、字体和图片及其他

2015-09-27 23:16 369 查看

[前端] 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: