canvas畫畫
- 坐標是以canvas的為標準的
- 畫長方形 :
- 畫圓形 :
- 畫線條:
- 寫文字:
- 寫了一個王字(代碼):
- 效果圖
1.基本語法:
html canvas 標簽:
是個盒子(有長,寬)和div相同,但可以在里面畫畫
<canvas id="canvas1" width="400px" height="400px"></canvas>
<script>
var canvas=document.getElementById("canvas1");
var ctx=canvas.getContext('2d');
</script>
坐標是以canvas的為標準的

開始畫:
畫長方形 :
ctx.fillStyle=“顏色”; 填充顏色
ctx.fillRect(矩形左上角x坐標 ,矩形左上角 y坐標, width, height, );
連續的對應的
ctx.fillStyle="black";
ctx.fillRect(0,0,20,20);
畫圓形 :
ctx.arc(x,y,radius,sAngle,eAngel,true);
false/true :順時針或者逆時針:畫圓形
sAngle 默認為0方便畫圓
x,y圓上的圓心坐標,radius為半徑,
sAngle:繪制開始的角度, 圓心到最右邊點是0度,順時針方向弧度增大,
eAngel:結束的角度,注意是弧度,
弧度和角度的轉換公式: rad = deg*Math.PI/180;
ctx.stroke(); 實線繪圓的框架/或者線條
ctx.fill(); 填充顏色(上一個設定的ctx.fillStyle)
2*Math.PI:周長 完整圓形
Math.PI :半圓形
ctx.arc(150,150,30,0,2*Math.PI,true);
ctx.stroke();
半圓形
ctx.fillStyle="pink";
ctx.arc(150,150,30,0,Math.PI,true);
ctx.stroke();
ctx.fill();
畫線條:
ctx.moveTo(x坐標, y坐標); 線條的起點
ctx.lineTo(x坐標, y坐標); 線條的終點
ctx.strokeStyle=“red” 線條顏色,
ctx.beginPath(); //重新開始一條路徑使顏色不互相影響
ctx.moveTo(10, 10);
ctx.lineTo(10,200);
ctx.stroke();
寫文字:
clearRect(X,Y, width, height)
clearRect() 方法清空給定矩形內的指定像素(清空矩形內內容)
ctx.clearRect(0, 0,600,600);
ctx.fillText(“文字”,x坐標, y坐標);
ctx.fillText("hello world!",100,200);
寫了一個王字(代碼):
<style>
canvas{
border: 2px solid black;
}
</style>
<body>
<canvas id="canvas1" width="400px" height="400px"></canvas>
<script>
var canvas=document.getElementById("canvas1");
var ctx=canvas.getContext("2d");
console.dir(ctx);
ctx.moveTo(30,30);
ctx.lineTo(300,30);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(30,170);
ctx.lineTo(300,170);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(30,300);
ctx.lineTo(300,300);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(150,30);
ctx.lineTo(150,300);
ctx.stroke();
</script>
效果圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304342.html
標籤:其他
上一篇:Vue體驗(前后端互動)
