svg 和 canvas
svg是:
一、矢量图,放大情况下不会产生马赛克(图形质量不会有所损失)。
二、SVG 是万维网联盟的标准。
三、可伸缩。
四、SVG 的主要竞争者是 Flash。(Flash慢慢在被淘汰)
五、通常用来设计图片,标签和css去绘制图像。
svg实例:
css样式:
<style>
*{
margin: 0;
padding: 0;
}
svg{
background-color: cornflowerblue;
}
</style>
标签内容:
<svg width='1000' height='1000' id='svg'>
<!-- 信封的多边形 -->
<polygon points='220,605 740,605 740,250 480,40 220,250 220,605' fill='white'></polygon>
<!-- 左线 -->
<line x1='222' y1='250' x2='222' y2='610' stroke='grey' stroke-width='6' stroke-dasharray='20'></line>
<!-- 下线 -->
<line x1='737' y1='250' x2='737' y2='605' stroke='grey' stroke-width='6' stroke-dasharray='20'></line>
<!-- 右线 -->
<line x1='225' y1='602' x2='737' y2='602' stroke='grey' stroke-width='6' stroke-dasharray='20'></line>
<!-- 右斜方线 -->
<line x1='737' y1='250' x2='480' y2='42' stroke='grey' stroke-width='6' stroke-dasharray='20'></line>
<!-- 左斜方线 -->
<line x1='223' y1='250' x2='480' y2='42' stroke='grey' stroke-width='6' stroke-dasharray='20'></line>
<!-- 左侧 -->
<line x1='220' y1='250' x2='430' y2='454' stroke='grey' stroke-width='2'></line>
<!-- 右侧 -->
<line x1='740' y1='250' x2='530' y2='456' stroke='grey' stroke-width='2'></line>
<!-- 信封折痕 -->
<line x1='740' y1='250' x2='220' y2='250' stroke='#EEEEEE' stroke-width='1'></line>
<!-- 下方折线 -->
<polyline points='220,605 480,420 740,605' fill-opacity='0' stroke='grey' stroke-width='2'></polyline>
<!-- 圆 -->
<circle fill='grey' cx='480' cy='430' r='40'></circle>
</svg>
实现效果:
canvas是:
一、像素图,放大之后会失真(出现马赛克)。
二、适合来设计动画 js去操控画布。
cancas实例:
css样式:
<style>
canvas{
background-color: pink;
}
</style>
标签内容:
<canvas width="1500" height="500"></canvas>
js代码:
<script>
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
// 将x轴的长度创建变量
var x = 100;
// 设置步长
var j = 1;
// 设置一个变量用于计时的动画效果
var flag = true;
// 设置计时器
var timer = setInterval(function(){
// 清除上一个画布
ctx.clearRect(0,0,1500,500);
// 开始一条新路径
ctx.beginPath();
// flag为true 则画张嘴的吃豆人
if(flag){
// 吃豆人
ctx.arc(x,300,50,0.2*Math.PI,Math.PI*1.8,0);
ctx.fillStyle = 'yellow';
ctx.strokeStyle = "transparent";
ctx.lineTo(x,300);
ctx.fill();
ctx.stroke();
// 眼睛
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.arc(x-10,280,5,0,Math.PI*2,0);
ctx.fill();
ctx.stroke();
x +=100;
flag = false;
}else{ // flag为false 则画闭嘴的吃豆人
// 吃豆人
ctx.arc(x,300,50,0,Math.PI*2,1);
ctx.fillStyle = 'yellow';
ctx.strokeStyle = "transparent";
ctx.lineTo(x,300);
ctx.fill();
ctx.stroke();
// 眼睛
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.arc(x-10,280,5,0,Math.PI*2,0);
ctx.fill();
ctx.stroke();
x +=100;
flag = true;
}
// 画豆豆
for(var i = j;i<15;i++){
console.log(i);
ctx.beginPath();
ctx.fillStyle = 'yellow';
ctx.arc((i*100-10), 300, 10, 0, Math.PI * 2, 0);
ctx.fill();
ctx.stroke();
}
// 如果移动距离大于等于画布的宽度 则将吃豆人从起始地方再开始
if(x>=1500){
x=100;
j=1;
}
j++;
},300);
</script>
实现效果: