第一个就是案例,加油!
准备(HTML)
,不提
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>W.html</title>
<style>
#canvas
{
position: fixed;
left: -20px;
top:-20px;
}
</style>
</head>
<body>
<canvas id="canvas" height="800" width = "1400"></canvas>
<script src="w.js"></script>
</body>
</html>
注意:在设置canvas的宽度与高度时,不能使用px后缀
(默认的canvas元素大小是300×150个屏幕像素)
后续
// (1)使用document.getElementById()方法[3]来获取指向canvas的引用。
var canvas = document.getElementById("canvas"),
// (2)在canvas对象上调用getContext('2d')方法,
// 获取绘图环境变量(注意,"2d"中的"d"必须小写)。
context = canvas.getContext('2d');
// (3)使用绘图环境对象在canvas元素上进行绘制。
context.strokeStyle = 'rgb(50,50,50)';
// context.font='38pt Arial'; 字体
// context.fillStyle='cornflowerblue';
// 清空画布
context.clearRect(0,0,canvas.clientWidth,canvas.height);
// 透明度
context.globalAlpha=0.5;
// strokeText()方法
// 使用strokeStyle属性来描绘字符的轮廓线。
context.strokeText('Hello',50,50);
// fillText() 使用fillStyle属性来填充文本中的字符,
fillStyle与strokeStyle属性可以是CSS格式的颜色、渐变色或是图案。
fillText()与strokeText()都需要3个参数:要绘制的文本内容,以及在canvas中显示文本的横、纵坐标。
version 2 后续
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
ctx.strokeStyle = 'blue';
var pos = [];
// push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度
document.onclick = (e)=>{
pos.push({x:e.pageX,y:e.pageY,n:50});
};
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
// array.forEach(function(currentValue, index, arr), thisValue)
// forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
pos.forEach((item,i)=>{
if(item.n>0){
ctx.globalAlpha = item.n/50;
ctx.strokeText("Hello,world",item.x,item.y);
item.y--;
item.n--;
};
else{
delete pos[i];
}
})
// setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。
setTimeout(
()=>{draw()}
,100);
}
draw();
做成了炫酷的特效