canvas動(dòng)畫(huà)思想
export class AppComponent implements OnInit{
canvas
ctx
left=100
ngOnInit(): void {
this.canvas = document.getElementById("canvas")
this.ctx = this.canvas.getContext("2d")
this.ctx.fillStyle = "blue"
//this.ctx.fillRect(100,100,100,100)
setInterval(()=>{
this.ctx.clearRect(0,0,300,300)
this.left++
this.ctx.fillRect(this.left,100,100,100)
},100)
console.log(this.ctx)
}
}
canvas 面向?qū)ο笏枷?/h3>
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//維護(hù)方法
function Rect(x,y,w,h,color){
this.x= x;
this.y= y;
this.w = w;
this.h=h;
this.color =color;
}
//更新方法察净,x坐標(biāo)加1(改變圖形位置)
Rect.prototype.update = function(){
this.x++;
}
//渲染方法
Rect.prototype.render = function(){
this.bind.ctx.fillStyle = "blue"
this.bind.ctx.fillRect(100,100,50,50,);
}
var r1 = new Rect(100,100,50,50,"blue")
setInterval(()=>{
this.ctx.clearRect(0,0,this.canvas.whdth,this.canvas.height)
r1.update()
r1.render()
// console.log("hello")
},1000)
console.log(this.ctx)
}
}
繪制矩形、直線
- 填充矩形
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//填充顏色
this.ctx.fillStyle = "blue"
//開(kāi)始繪制填充矩形
this.ctx.fillRect(100,100,100,100)
console.log(this.ctx)
}
}
- 矩形邊框
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//邊框顏色
this.ctx.strokeStyle="red"
//開(kāi)始繪制
this.ctx.strokeRect(100,100,100,100)
console.log(this.ctx)
}
}
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//維護(hù)方法
function Rect(x,y,w,h,color){
this.x= x;
this.y= y;
this.w = w;
this.h=h;
this.color =color;
}
//更新方法察净,x坐標(biāo)加1(改變圖形位置)
Rect.prototype.update = function(){
this.x++;
}
//渲染方法
Rect.prototype.render = function(){
this.bind.ctx.fillStyle = "blue"
this.bind.ctx.fillRect(100,100,50,50,);
}
var r1 = new Rect(100,100,50,50,"blue")
setInterval(()=>{
this.ctx.clearRect(0,0,this.canvas.whdth,this.canvas.height)
r1.update()
r1.render()
// console.log("hello")
},1000)
console.log(this.ctx)
}
}
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//填充顏色
this.ctx.fillStyle = "blue"
//開(kāi)始繪制填充矩形
this.ctx.fillRect(100,100,100,100)
console.log(this.ctx)
}
}
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//邊框顏色
this.ctx.strokeStyle="red"
//開(kāi)始繪制
this.ctx.strokeRect(100,100,100,100)
console.log(this.ctx)
}
}
擦除畫(huà)布
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
- 繪制路徑
(逆時(shí)針繪制)
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
//創(chuàng)建一個(gè)路徑
this.ctx.beginPath()
//移動(dòng)畫(huà)筆繪制點(diǎn)
this.ctx.moveTo(100,100)
//描述行進(jìn)路徑節(jié)點(diǎn)
this.ctx.lineTo(200,200)
this.ctx.lineTo(400,180)
this.ctx.lineTo(380,50)
//封閉路徑
this.ctx.closePath()
//畫(huà)筆顏色
this.ctx.strokeStyle = 'red'
//開(kāi)始繪制
this.ctx.stroke()
}
}
線條可以不封閉---this.ctx.closePath()锅必,但fill會(huì)自動(dòng)封閉
繪制圓弧
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//獲取畫(huà)布
this.canvas = document.getElementById("canvas")
//獲取上下文
this.ctx = this.canvas.getContext("2d")
this.ctx.arc(200,200,100,0,2*Math.PI,false)
//this.ctx.arc(200,200,100,0,2*3.14,false)
this.ctx.fill() //填充
// this.ctx.stroke() //邊框
}
}
鼠標(biāo)炫彩小球效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
canvas{
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas")
var ctx = canvas.getContext("2d")
//console.log(ctx)
function Ball(x,y,r){
this.x = x;
this.y = y;
this.r = r;
this.color = getRandom();
this.dx = parseInt(Math.random()*10)-5;//(0事格,10)-5 = (-5,5)
this.dy = parseInt(Math.random()*10)-5;
ballArr.push(this)
console.log(this)
}
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
this.r -= 0.4;
if(this.r<0){
this.remove()
}
};
Ball.prototype.remove = function(){
for(var i=0;i<ballArr.length;i++){
if(ballArr[i]==this){
ballArr.splice(i,1);
}
}
};
Ball.prototype.render = function(){
ctx.beginPath()
ctx.arc(this.x,this.y,this.r,0 ,Math.PI*2,false)
ctx.fillStyle = this.color;
ctx.fill()
}
//監(jiān)聽(tīng)canvas搞隐,傳人當(dāng)前x驹愚、y軸偏移和繪圖半徑
canvas.addEventListener("mousemove",function(event){
new Ball(event.offsetX,event.offsetY,30)
})
var ballArr = []
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(var i=0;i<ballArr.length;i++){
ballArr[i].update()
if(ballArr[i]){
ballArr[i].render()
}
}
},100)
//產(chǎn)生一個(gè)隨機(jī)的16進(jìn)制顏色
function getRandom(){
var allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
var allTypeArr = allType.split(",")
//console.log(allTypeArr)
var color = "#"
for(var i =0;i<6;i++){
var random = parseInt(Math.random()*allTypeArr.length);
color+=allTypeArr[random];
}
return color;
}
console.log(getRandom())
</script>
</body>
</html>
小球觸邊反彈
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
canvas{
display: block;
border: 1px solid #000000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="" height=""></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas")
var ctx=canvas.getContext("2d");
console.log(ctx)
canvas.width = document.documentElement.clientWidth-30;
canvas.height = document.documentElement.clientHeight-30;
//console.log(canvas.width,canvas.height)
function Ball(){
this.x = parseInt(Math.random()*canvas.width);
this.y = parseInt(Math.random()*canvas.height);
//console.log(this.x,this.y)
this.color = "blue";
this.r = 10;
this.dx = parseInt(Math.random()*10)-5;
this.dy = parseInt(Math.random()*10)-5;
//console.log(this.dx,this.dy)
ballArr.push(this);
}
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
if(this.x < this.r || this.x >canvas.width-this.r){
this.dx = -this.dx
}
if(this.y < this.r || this.y > canvas.height-this.r){
this.dy = -this.dy
}
}
Ball.prototype.render = function(){
ctx.beginPath();
ctx.globalAlpha = 1;
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.fillStyle = this.color;
ctx.fill();
}
var ballArr = [];
for(var i =0;i<20;i++){
new Ball()
}
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(var i = 0;i<ballArr.length;i++){
ballArr[i].update()
ballArr[i].render()
}
},20)
</script>
</body>
</html>
小球靠近連線
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
canvas{
display: block;
border: 1px solid #000000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="" height=""></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas")
var ctx=canvas.getContext("2d");
console.log(ctx)
canvas.width = document.documentElement.clientWidth-30;
canvas.height = document.documentElement.clientHeight-30;
//console.log(canvas.width,canvas.height)
function Ball(){
this.x = parseInt(Math.random()*canvas.width);
this.y = parseInt(Math.random()*canvas.height);
//console.log(this.x,this.y)
this.color = "blue";
this.r = 10;
this.dx = parseInt(Math.random()*10)-5;
this.dy = parseInt(Math.random()*10)-5;
//console.log(this.dx,this.dy)
ballArr.push(this);
this.index = ballArr.length - 1;
}
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
if(this.x < this.r || this.x >canvas.width-this.r){
this.dx = -this.dx
}
if(this.y < this.r || this.y > canvas.height-this.r){
this.dy = -this.dy
}
}
Ball.prototype.render = function(){
ctx.beginPath();
ctx.globalAlpha = 1;
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.fillStyle = this.color;
ctx.fill();
for(var i= this.index;i < ballArr.length;i++){
if(Math.abs(ballArr[i].x - this.x) < 150&&Math.abs(ballArr[i].y-this.y )< 150){
ctx.strokeStyle = "#000000";
ctx.globalAlpha = 10 / Math.sqrt(Math.pow(ballArr[i].x-this.x,2)+Math.pow(ballArr[i].x - this.x,2))
ctx.beginPath();
ctx.moveTo(this.x,this.y);
ctx.lineTo(ballArr[i].x,ballArr[i].y);
ctx.closePath()
ctx.stroke()
}
}
}
var ballArr = [];
for(var i =0;i<20;i++){
new Ball()
}
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(var i = 0;i<ballArr.length;i++){
ballArr[i].update()
ballArr[i].render()
}
},20)
</script>
</body>
</html>
線型
渲染圖片到畫(huà)布
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas{
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="mycanva" width="700" height="700"></canvas>
<script>
var canvas = document.getElementById("mycanva")
var ctx = canvas.getContext("2d")
var image = new Image()
image.src = "./star.jpg"
console.log(image.src)
image.onload = function(){
ctx.drawImage(image,100,100,50,50)
}
</script>
</body>
</html>
資源管理器的封裝
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="" width="600" height="500"></canvas>
<script type="text/javascript">
function Game(){
this.dom = document.querySelector("canvas");
this.ctx = dom.getContextP("2d");
//添加屬性,保持圖片地址
this.R = {
"gugong":"./images/0.jpg",
"niaochao":"./images/1.jpg",
"yiheyuan":"./images/2.jpg",
"tiantan":"./images/3.jpg",
"guojiadajuyuan":"./images/4.jpg"
};
//獲取資源圖片總數(shù)
var allAmount = Object.keys(this.R).length;
console.log(allAmount)
//計(jì)數(shù)器(記錄加載完畢的數(shù)量)
var count = 0;
for(k in this.R){
//備份每一張圖片的地址
var src = this.R[k];
//創(chuàng)建一張圖片
this.R[k] = new Image();
//賦值src圖片地址
this.R[k].src = src;
//
this.R[k].onload = function(){
count++;
//console.log(count,allAmount)
//清屏
self.ctx.clearRect(0,0,600,500)
self.ctx.font = "16px Arial";
//設(shè)置資源加載文案
self.ctx.fillText("圖片已經(jīng)加載:" + cuont + "/“ + allAmount,10,50)
//
if(count == allAmount){
self.start();
}
}
}
}
Game.prototype.start = function(){
var self = this;
this.ctx.drawImage(this.R["gugong"],200,200,100,80)
//開(kāi)啟定時(shí)器
//
}
console.log(new Game)
</script>
</body>
</html>
變形
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="" width="600" height="500"></canvas>
<script type="text/javascript">
function draw(){
var dom = document.querySelector("canvas");
var ctx = dom.getContext("2d");
ctx.fillRect(0,0,150,150);
ctx.save() //保存
ctx.fillStyle = '#09f'
ctx.fillRect(15,15,120,120)
ctx.save()//保存
ctx.fillStyle = '#fff'
ctx.fillRect(30,30,90,90)
// ctx.save()
ctx.restore() //撤銷
ctx.fillRect(45,45,60,60)
ctx.restore() //撤銷
ctx.fillRect(60,60,30,30)
}
draw()
</script>
</body>
</html>
<canvas id="" width="600" height="500"></canvas>
<script type="text/javascript">
function draw(){
var dom = document.querySelector("canvas");
var ctx = dom.getContext("2d");
ctx.save()
ctx.translate(50,50)
ctx.fillRect(0,0,120,120)
ctx.restore()
ctx.fillRect(0,200,120,120)
}
draw()
</script>
刮刮樂(lè)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
position: relative;
width: 300px;
height: 70px;
border: 1px solid #000;
margin: 100px;
text-align: center;
line-height: 70px;
font-size: 30px;
}
canvas{
position: absolute;
left: 0;
top: 0%;
/* background-color: #000; */
}
</style>
</head>
<body>
<div class="box">
中獎(jiǎng)100萬(wàn)
<canvas id="" width="300" height="70"></canvas>
</div>
<script>
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d")
ctx.fillStyle = "#000"
ctx.fillRect(0,0,300,70)
ctx.globalCompositeOperation = "destination-out"
canvas.onmousedown = function(){
console.log("鼠標(biāo)按下")
canvas.onmousemove = function(){
console.log("拖動(dòng)了")
ctx.beginPath()
ctx.arc(event.offsetX,event.offsetY,10,0,7,false)
ctx.fill()
}
}
</script>
</body>
</html>
拖拽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas{
position: absolute;
left: 0;
top: 0%;
border: 1px solid #000;
/* background-color: #000; */
}
</style>
</head>
<body>
<canvas id="" width="500" height="500"></canvas>
<script>
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d")
const statusConfig = {
IDLE:0,
DRAG_START:1,
DRAGGING:2,
}
const canvasInfo = {
status:statusConfig.IDLE,
dragTraget:null,
lastEvtPos:{x:null,y:null},
offsetEvtpos:{x:null,y:null}
}
const circles = []
const drawCircle = (ctx,cx,cy,r)=>{
ctx.save()
ctx.beginPath()
ctx.strokeStyle = 'blue'
ctx.arc(cx,cy,r,0,Math.PI*2)
ctx.stroke()
ctx.closePath()
ctx.restore()
}
drawCircle(ctx,100,100,20)
circles.push({
x:100,
y:100,
r:20
})
drawCircle(ctx,200,200,10)
circles.push({
x:200,
y:200,
r:10
})
// console.log(circles)
const getCanvansPosition= e=>{
return {
x:e.offsetX,
y:e.offsetY
}
}
const getDistance = (p1,p2)=>{
return Math.sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2)
}
const ifInCircle=(pos)=>{
for(let i = 0;i < circles.length;i++){
if(getDistance(circles[i],pos) < circles[i].r){
return circles[i]
}
}
return false
}
canvas.addEventListener('mousedown',e=>{
//console.log( getCanvansPosition(e))
const canvasPosition = getCanvansPosition(e)
// console.log(ifInCircle(canvasPosition))
const circleRef = ifInCircle(canvasPosition)
if(circleRef){
canvasInfo.dragTraget = circleRef;
canvasInfo.status = statusConfig.DRAG_START
canvasInfo.lastEvtPos = canvasPosition
//console.log(circles)
canvasInfo.offsetEvtpos = canvasPosition
}
})
canvas.addEventListener('mousemove',e =>{
const canvasPosition = getCanvansPosition(e)
if(ifInCircle(canvasPosition)){
canvas.style.cursor = 'all-scroll'
}else{
canvas.style.cursor =''
}
// const canvasPosition = getCanvansPosition(e)
if(canvasInfo.status ===statusConfig.DRAG_START&&getDistance(canvasPosition,canvasInfo.lastEvtPos)>5){
console.log("dlksfjslk")
canvasInfo.status = statusConfig.DRAGGING
canvasInfo.offsetEvtpos = canvasPosition
}else if(canvasInfo.status === statusConfig.DRAGGING){
console.log('dragging')
// const {dragTarget} = canvasInfo
console.log("999999999999",canvasInfo)
canvasInfo.dragTraget.x += (canvasPosition.x - canvasInfo.offsetEvtpos.x)
canvasInfo.dragTraget.y += ( canvasPosition.y - canvasInfo.offsetEvtpos.y)
ctx.clearRect(0,0,canvas.width,canvas.height)
circles.forEach(c=>drawCircle(ctx,c.x,c.y,c.r))
canvasInfo.offsetEvtpos = canvasPosition
}
})
canvas.addEventListener('mouseup',e=>{
if(canvasInfo.status === statusConfig.DRAGGING){
canvasInfo.status = statusConfig.IDLE
}
})
</script>
</body>
</html>