2019.9.5绘图

Web前端中的绘图技术

canvas技术 ---2D图像/图形
SVG技术 ---矢量图
WebGL 3D图形/图像 不在HTML5 的标准中

今天主要来讲讲画布canvas

<canvas width="600" height="400" id="can"></canvas>
注意,宽高要在标签上设置而不能再CSS样式中设置

var canvas = document.getElementById('can');
 获取画笔 获得绘图上下文 content内容 context上下文
var ctx = canvas.getContext('2d');

矩形
var x=0,y=0,w=100,h=80;
ctx.fillRect(x,y,w,h);//填充一个矩形rectangle 左上角
ctx.fillRect(500,0,w,h);//右上角
ctx.fillRect(0,320,w,h);//左下角
ctx.fillRect(500,320,w,h);//右下角
ctx.fillStyle = "#f00";
ctx.fillRect(600/2-50,400/2-40,w,h);//正中间
// 设置描边的宽度 开始绘制之前设置宽度
// ctx.lineWidth = 10;
// 描边的矩形
// ctx.strokeRect(0+5,0+5,100,80);

 

要求:

// 在600*400的画布中绘制
// 1、左上角填充一个100*80的矩形,默认颜色
// 2、右上角填充一个100*80的矩形,默认颜色
// 3、右下角填充一个矩形100*80.默认颜色
// 4、右下角描边一个矩形100*80,青色
// 5、在正中央填充一个描边矩形100*80,注意是什么颜色
// 6、重新创建一个画布,使用定时器,绘制一个可以不断向右移动的矩形
// 7、绘制一个斜向30度角移动的矩形

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
text-align: center;
}
canvas{
background-color: #abcdef;
}
</style>
</head>
<body>
<canvas width="600" height="400" id="can"></canvas>
<canvas width="600" height="400" id="can1"></canvas><br>
<canvas width="600" height="400" id="can0"></canvas>
<canvas width="600" height="400" id="can2"></canvas>
<script>
var can = document.getElementById('can');
var ctx = can.getContext('2d');
ctx.fillRect(0,0,100,80);
ctx.fillRect(500,0,100,80);
ctx.fillRect(500,320,100,80);

ctx.lineWidth = 10;
ctx.strokeStyle = '#0ff';
ctx.strokeRect(495,315,100,80)

ctx.fillRect(250,160,100,80)
ctx.strokeRect(250,160,100,80)

不断右移的矩形
var can1 = document.getElementById('can1');
var ctx1 = can1.getContext('2d'),m = 0,n = 0;
setInterval(function(){
ctx1.clearRect(0,0,600,400)
m += 10;
ctx1.strokeRect(m,0,100,80)
},30)

 

斜着移的矩形

var can0 = document.getElementById('can0');
var ctx0 = can0.getContext('2d');
var m= 0,n = 0;
setInterval(function(){
ctx0.clearRect(0,0,600,400)
m += 5;
n += Math.tan(Math.PI/180 * 30)*5
ctx1.strokeRect(m,n,100,80)
},30)

 

360度转圈的矩形

var can2 = document.getElementById('can2');
var ctx2 = can2.getContext('2d'),x = 0,y = 0,r = 100,num = 50;
setInterval(function(){
ctx2.clearRect(0,0,600,400);
num += 5;
y = Math.sin(num*Math.PI/180)*r;
x = Math.cos(num*Math.PI/180)*r;
ctx2.strokeRect(x+300,y+150,100,80)
},30)
</script>
</body>
</html>

posted @ 2019-09-23 21:04  矜鸾  阅读(133)  评论(0编辑  收藏  举报