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); }
相关文章推荐
- *LeetCode-Count Primes
- 生命游戏(Game Of Life)结对编程体验
- Thread 两种实现方式的区别
- Java下利用Jedis开发Redis
- jquery中html()/text()/val()区别
- Linux-Ubuntu14.04 通过mentohust实现锐捷校园网安装与认证
- 单例模式、双检测锁定DCL、volatile
- 制作导航栏
- C++中重载与重写的理解
- Java Web开发2___<jsp:include>和<%@ include %>的区别
- 2015第39周日
- iPhone指纹解锁功能设置
- iPhone指纹解锁功能设置
- poj 1404 I-Keyboard dp输出方案
- webrtc 后台搭建步骤及原理
- windows 测试数据库的连接状况-udl方法
- leetcode009 Palindrome Number
- 17、一般网络命令
- AO中的GraphicsLayer---------元素的容器
- 欧拉回路 (Euler Circuit) POJ 1780