創(chuàng)建一個canvas
HTML
創(chuàng)建canvas元素
<canvas id="canvas"></canvas>
設置寬高使用標簽width,height屬性,注意不能使用css或style樣式
display默認為inline
<canvas id="canvas" width="1024" height="768" style="border: 1px solid #ccc; display: block; margin: 0 auto;">當前瀏覽器不支持canvas,請更換瀏覽器后再試</canvas>
JavaScript
獲取canvas
//獲取canvas元素
var canvas = document.getElementById('canvas')
//使用context進行繪制
var context = canvas.getCountext('2d');
除了通過上面HTML屬性設置canvas寬高之外,當然也可以用javascript來設置
canvas.width = 1024
canvas.height = 768
也可以使用javascript檢測瀏覽器是否支持canvas
if(canvas.getContext('2d')){
var context = canvas.getCountext('2d');
}else{
alert('當前瀏覽器不支持canvas,請更換瀏覽器后再試')
}
補充——解決vscode編輯canvas沒有代碼提示問題
在定義canvas之前加入如下注釋即可
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas')
畫一條直線
畫布左上角坐標為默認為(0,0),那么我想畫一條坐標從(100,100)到(700,700)的直線,該怎么畫呢?
//起筆
context.beginPath()
//路徑
context.moveTo(100, 100)
context.lineTo(700, 700)
//落筆
context.closePath()
//繪制路徑
context.stroke()
beginPath(),closePath()
beginPath()重新規(guī)劃一條路線
closePath()結束當前的路線,如果當前的路線沒有封閉則會自動封閉路線
只繪制一個圖形時可以省略這兩個方法,但是如果當你再畫第二個圖形時,下面的context.stroke()會把上面的覆蓋,所以注意beginPath(),closePath()的使用
closePath()的另外一個作用就是封閉圖形,如果繪制多個圖形又不想封閉圖形該怎么做呢?這里可以只寫beginPath()省略后面的closePath(),從而繪制多個圖形時都不會產生影響,beginPath(),closePath()不一定要成對出現
beginPath()后的moveTo()可以被lineTo()代替,即可以不寫moveTo(),詳見下面畫五角星中的應用。
線條屬性
linewidth
線條寬度,屬性值為數字
lineCap
線條的邊角,注意這個屬性的頭是突出的,所以比默認線條長度兩邊各多出一個半徑的長度。lineCap只有線條首尾有效果,線條銜接處無效。銜接處使用lineJoin
| 值 | 描述 |
|---|---|
| butt | 默認。向線條的每個末端添加平直的邊緣。 |
| round | 向線條的每個末端添加圓形線帽。 |
| square | 向線條的每個末端添加正方形線帽。 |
lineJoin
當兩條線條交匯時,創(chuàng)建邊角
| 值 | 描述 |
|---|---|
| bevel | 創(chuàng)建斜角。 |
| round | 創(chuàng)建圓角。 |
| miter | 默認。創(chuàng)建尖角。 |
miterLimit
畫一個三角形
context.beginPath()
//路徑
context.moveTo(100, 100)
context.lineTo(700, 700)
context.lineTo(100, 700)
//封閉
context.closePath()
context.stroke()
把線條粗細改成5個像素,顏色為紅色
context.lineWidth = 5
context.strokeStyle = 'red'
填充封閉空間
//填充顏色
context.fillStyle = '#38f'
context.fill();
補充——stroke和fill調用先后順序對繪圖的影響
先調用stroke在調用fill,繪制的效果看上去lineWidth只繪制出來一半,這是因為先填充會把邊框覆蓋掉一半,正確順序是先調用fill在調用stroke,用邊框顏色去覆蓋填充顏色就能達到理想效果。
補充——canvas的”狀態(tài)“和”繪制“代碼書寫技巧
canvas是基于狀態(tài)進行繪制的,在編程中可以把狀態(tài)和繪制分開寫,這樣會更加直觀簡潔。例如:
// 路徑
context.beginPath()
context.moveTo(100, 100)
context.lineTo(700, 700)
context.lineTo(100, 700)
context.closePath()
// 狀態(tài)
context.lineWidth = 5
context.fillStyle = '#38f'
context.strokeStyle = 'red'
// 繪制
context.fill();
context.stroke()
繪制七巧板
參考代碼如下,注意beginPath(),closePath()的位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas-七巧板</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid #ccc; display: block; margin: 0 auto;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
var tangram = [
{ trajectory: [ {x: 0, y: 0}, {x: 800, y: 0}, {x: 400, y: 400} ], color: '#caff67' },
{ trajectory: [ {x: 0, y: 0}, {x: 400, y: 400}, {x: 0, y: 800} ], color: '#67becf' },
{ trajectory: [ {x: 800, y: 0}, {x: 800, y: 400}, {x: 600, y: 600}, {x: 600, y: 200} ], color: '#ef3d61' },
{ trajectory: [ {x: 600, y: 200}, {x: 600, y: 600}, {x: 400, y: 400} ], color: '#f9f51a' },
{ trajectory: [ {x: 400, y: 400}, {x: 600, y: 600}, {x: 400, y: 800}, {x: 600, y: 600} ], color: '#a594c0' },
{ trajectory: [ {x: 200, y: 600}, {x: 400, y: 800}, {x: 0, y: 800} ], color: '#fa8ecc' },
{ trajectory: [ {x: 800, y: 400}, {x: 800, y: 800}, {x: 400, y: 800} ], color: '#f6ca29' }
]
// 繪制
function draw(piece, cxt){
cxt.beginPath()
cxt.moveTo(piece.trajectory[0].x, piece.trajectory[0].y)
for(var j = 1; j < piece.trajectory.length; j ++){
cxt.lineTo(piece.trajectory[j].x, piece.trajectory[j].y)
}
cxt.closePath()
cxt.fillStyle = piece.color
cxt.fill();
}
window.onload = function(){
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
canvas.width = 800
canvas.height = 800
for(var i = 0; i < tangram.length; i ++){
draw(tangram[i], context)
}
}
</script>
</body>
</html>
畫一個圓弧
//x:圓的中心的 x 坐標
//y:圓的中心的 y 坐標
//r:圓的半徑
//sAngle:起始角,以弧度計。(弧的圓形的三點鐘位置是 0 度)
//eAngle:結束角,以弧度計
//counterclockwise:可選。規(guī)定應該逆時針還是順時針繪圖。False = 順時針,true = 逆時針。默認順時針
context.arc(x,y,r,sAngle,eAngle,counterclockwise);
畫一個圓弧
context.beginPath()
context.arc(400, 400, 100, 0, 1.5*Math.PI, false)
context.closePath()
context.stroke()
如果不想封閉,刪除context.closePath()即可
畫一個圓
弧度從0到2π即可
context.beginPath()
context.arc(400, 400, 100, 0, 2*Math.PI, false)
context.stroke()
小球落體運動
參考代碼
注意:測試時最好注釋render()中的第一行代碼
cxt.clearRect(0, 0, WIDTH, HEIGHT),這樣可以顯示出運動軌跡。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>ball-fall</title>
</head>
<body>
<canvas id="canvas" style="border: 2px solid #ccc; display: block; margin: 20px auto 0;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
var ball = {x: 900, y: 200, vx: -4, vy: 0, g: 1.5}
var WIDTH = 1000, HEIGHT = 700, RIDIUS = 15
window.onload = function(){
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
canvas.width = WIDTH
canvas.height = HEIGHT
setInterval(function(){
render(context)
update()
}, 50)
}
function render(cxt){
cxt.clearRect(0, 0, WIDTH, HEIGHT)
cxt.beginPath()
cxt.arc(ball.x, ball.y, RIDIUS, 0, 2*Math.PI)
cxt.closePath()
cxt.fillStyle = '#f0f'
cxt.fill();
}
function update(){
ball.x += ball.vx
ball.y += ball.vy
if(ball.y >= HEIGHT-RIDIUS){
ball.y = HEIGHT-RIDIUS
ball.vy = -ball.vy*0.7
}else{
ball.vy += ball.g
}
}
</script>
</body>
</html>
代碼中首先定義了小球的基本屬性:橫坐標,縱坐標,水平速度,垂直速度,加速度
update()中用到了一個摩擦系數為0.7
update()
這里的重點是update函數部分,為什么會這樣寫?示例代碼用到了摩擦系數0.7,運動軌跡看起來差別不大。如果沒有摩擦,觀察下面幾種寫法有什么不同。
// 方法一
function update(){
ball.x += ball.vx
ball.y += ball.vy
ball.vy += ball.g
if(ball.y >= HEIGHT-RIDIUS){
ball.y = HEIGHT-RIDIUS
ball.vy = -ball.vy
// 測試打印出最大垂直速度
console.log(ball.vy)
}
}
// 方法二
function update(){
ball.x += ball.vx
ball.y += ball.vy
if(ball.y >= HEIGHT-RIDIUS){
ball.y = HEIGHT-RIDIUS
ball.vy = -ball.vy
// 測試打印出最大垂直速度
console.log(ball.vy)
}
ball.vy += ball.g
}
// 方法三
function update(){
ball.x += ball.vx
ball.y += ball.vy
if(ball.y >= HEIGHT-RIDIUS){
ball.y = HEIGHT-RIDIUS
ball.vy = -ball.vy
// 測試打印出最大垂直速度
console.log(ball.vy)
}else{
ball.vy += ball.g
}
}
這幾種方法都沒有摩擦系數,僅僅只是
ball.vy += ball.g的位置不同而已,經過測試你會發(fā)現:方法一彈跳后最高點會越來越高,方法二彈跳后最高點會越來越低,而方法三則都在同一最高點。通過打印出的最大垂直速度不難發(fā)現,方法一造成的原因是每次小球落到最低點都多加了一次ball.g,方法二同理。方法三是在水平線以上才會累加垂直速度。
上拋效果
其實上拋效果很簡單,只需要將
ball.vy的初始值設置為負值即可,這里需要注意ball.vy的值盡量按照加速度的值來設定,最好是加速度的倍數,這樣能夠保證最高點的垂直速度為0,運動軌跡都有統(tǒng)一的焦點。這里還有一個問題:設置過上拋效果后,第一個最高點可能和之后的最高點不同,造成這個原因是因為小球落到最低處時的位置不一定剛好等于
HEIGHT-RIDIUS,示例代碼中是強制不讓小球出界。如下
if(ball.y >= HEIGHT-RIDIUS){
ball.y = HEIGHT-RIDIUS
}
如果注釋
ball.y = HEIGHT-RIDIUS這行代碼你會發(fā)現路徑的最高點都一樣了。這里最簡單的解決方法就是調整ball的初始位置,使其下落到最低點時剛好是邊界的高度,即
ball.y == HEIGHT-RIDIUS
動態(tài)粒子時鐘效果
參考代碼 演示 ,digit.js文件地址
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>canvas-clock</title>
<style>
* {margin: 0; padding: 0;}
</style>
</head>
<body>
<canvas id="canvas" style="display: block;background-color: black;">當前瀏覽器不支持canvas,請更換瀏覽器后再試</canvas>
<script>
var WIDTH, HEIGHT, LEFT, TOP, RADIUS, timeSeconds, balls = [], timer
window.onload = function () {
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 自適應窗口大小
WIDTH = document.documentElement.clientWidth
HEIGHT = document.documentElement.clientHeight
// 邊距(先計算RADIUS)
RADIUS = Math.round(WIDTH / 170)
LEFT = Math.round((WIDTH - 107 * RADIUS) / 2)
TOP = Math.round((HEIGHT - 20 * RADIUS) / 3)
timeSeconds = getTime()
// 畫布寬高
canvas.width = WIDTH
canvas.height = HEIGHT
animation(context)
// 監(jiān)聽當前頁面是否被隱藏
document.addEventListener('visibilitychange', function () {
if (document.visibilityState == 'hidden') {
clearInterval(timer)
} else if (document.visibilityState == 'visible') {
animation(context)
}
})
}
// 小球下落動畫
function animation(context) {
timer = setInterval(function () {
render(context)
update()
}, 50)
}
// 渲染頁面
function render(cxt) {
var hours = parseInt(timeSeconds / 3600),
minutes = parseInt((timeSeconds - hours * 3600) / 60)
seconds = timeSeconds % 60
// 首先清空畫布
cxt.clearRect(0, 0, WIDTH, HEIGHT)
renderDigit(LEFT, TOP, parseInt(hours / 10), cxt)
renderDigit(LEFT + 15 * RADIUS, TOP, parseInt(hours % 10), cxt)
renderDigit(LEFT + 30 * RADIUS, TOP, 10, cxt)
renderDigit(LEFT + 39 * RADIUS, TOP, parseInt(minutes / 10), cxt)
renderDigit(LEFT + 54 * RADIUS, TOP, parseInt(minutes % 10), cxt)
renderDigit(LEFT + 69 * RADIUS, TOP, 10, cxt)
renderDigit(LEFT + 78 * RADIUS, TOP, parseInt(seconds / 10), cxt)
renderDigit(LEFT + 93 * RADIUS, TOP, parseInt(seconds % 10), cxt)
// 渲染下落的小球
for (var i = 0; i < balls.length; i++) {
cxt.fillStyle = balls[i].color
cxt.beginPath()
cxt.arc(balls[i].x, balls[i].y, RADIUS, 0, 2 * Math.PI, true)
cxt.closePath()
cxt.fill()
}
}
// 更新畫布
function update() {
var nextTimeSeconds = getTime(),
nextHours = parseInt(nextTimeSeconds / 3600),
nextMinutes = parseInt((nextTimeSeconds - nextHours * 3600) / 60),
nextSeconds = nextTimeSeconds % 60,
curHours = parseInt(timeSeconds / 3600),
curMinutes = parseInt((timeSeconds - curHours * 3600) / 60),
curSeconds = timeSeconds % 60
if (nextSeconds !== curSeconds) {
// 判斷被改變的數字,判斷小球位置
if (parseInt(curHours / 10) != parseInt(nextHours / 10)) {
addBalls(LEFT + 0, TOP, parseInt(curHours / 10))
}
if (parseInt(curHours % 10) != parseInt(nextHours % 10)) {
addBalls(LEFT + 15 * RADIUS, TOP, parseInt(curHours / 10))
}
if (parseInt(curMinutes / 10) != parseInt(nextMinutes / 10)) {
addBalls(LEFT + 39 * RADIUS, TOP, parseInt(curMinutes / 10))
}
if (parseInt(curMinutes % 10) != parseInt(nextMinutes % 10)) {
addBalls(LEFT + 54 * RADIUS, TOP, parseInt(curMinutes % 10))
}
if (parseInt(curSeconds / 10) != parseInt(nextSeconds / 10)) {
addBalls(LEFT + 78 * RADIUS, TOP, parseInt(curSeconds / 10))
}
if (parseInt(curSeconds % 10) != parseInt(nextSeconds % 10)) {
addBalls(LEFT + 93 * RADIUS, TOP, parseInt(nextSeconds % 10))
}
// 同步顯示時間
timeSeconds = nextTimeSeconds
}
updateBalls()
}
// 按照數字添加小球個數
function addBalls(x, y, num) {
for (var i = 0; i < digit[num].length; i++){
for (var j = 0; j < digit[num][i].length; j++){
if (digit[num][i][j] == 1) {
var aBall = {
x: x + j * 2 * RADIUS + RADIUS,
y: y + i * 2 * RADIUS + RADIUS,
g: 1.5 + Math.random(),
vx: Math.pow(-1, Math.ceil(Math.random() * 1000)) * 4,
vy: -5,
color: getRandomColor()
}
balls.push(aBall)
}
}
}
}
// 更新下落小球的位置
function updateBalls() {
for (var i = 0; i < balls.length; i++) {
balls[i].x += balls[i].vx
balls[i].y += balls[i].vy
// 反彈效果
if (balls[i].y >= HEIGHT - RADIUS) {
balls[i].y = HEIGHT - RADIUS
balls[i].vy = - Math.abs(balls[i].vy) * 0.75
}else{
balls[i].vy += balls[i].g
}
}
// 刪除超出界面外的小球
for (var i = 0; i < balls.length; i++) {
if (balls[i].x + RADIUS < 0 || balls[i].x - RADIUS > WIDTH) {
balls.splice(i, 1)
}
}
}
// 獲取時間
function getTime() {
var curTime = new Date()
return curTime.getHours() * 3600 + curTime.getMinutes() * 60 + curTime.getSeconds()
}
// 渲染數字
function renderDigit(x, y, num, cxt) {
cxt.fillStyle = "rgb(0,102,153)"
for (var i = 0; i < digit[num].length; i++) {
for (var j = 0; j < digit[num][i].length; j++) {
if (digit[num][i][j] == 1) {
cxt.beginPath()
cxt.arc(x + j * 2 * RADIUS + RADIUS, y + i * 2 * RADIUS + RADIUS, RADIUS, 0, 2 * Math.PI)
cxt.closePath()
cxt.fill()
}
}
}
}
// 獲取隨機顏色
function getRandomColor() {
return '#' +
(function (color) {
return (color += '5678956789defdef'[Math.floor(Math.random() * 16)]) &&
(color.length == 6) ? color : arguments.callee(color)
})('')
}
</script>
<script src="./digit.js"></script>
</body>
</html>
畫一個矩形
通過上面的方法,已經可以用線條畫出一個封閉矩形,除此之外canvas還為我們提供了直接繪制矩形的方法。調用即可
context.rect(x,y,width,height)
context.fillRect(x,y,width,height)
context.strokeRect(x,y,width,height)
畫一個五角星
參考代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>start</title>
</head>
<body>
<canvas id="canvas" style="border: 2px solid #ccc; display: block; margin: 20px auto 0;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
window.onload = function(){
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
canvas.width = 800
canvas.height = 700
context.lineWidth = 10
drawStart(context, 150, 300, 400, 400)
}
// 小圓半徑,大圓半徑,x,y坐標,順時針旋轉角度(默認0)
function drawStart(cxt, r, R, x, y, rot = 0){
cxt.beginPath()
for(var i = 0; i < 5; i ++){
cxt.lineTo(Math.cos((18 + i*72 - rot)/180 * Math.PI) * R + x,
-Math.sin((18 + i*72 - rot)/180 * Math.PI) * R + y)
cxt.lineTo(Math.cos((54 + i*72 - rot)/180 * Math.PI) * r + x,
-Math.sin((54 + i*72 - rot)/180 * Math.PI) * r + y)
}
cxt.closePath()
cxt.stroke()
}
</script>
</body>
</html>
思路:五角星的五個內頂點在小圓上,外頂點在大圓上。以圓心為坐標原點,五角星上頂點在y軸,建立坐標系,注意canvas中y軸方向向下。五角星中每個頂點坐標相差72度,簡單計算即可得到五角星各個頂點的位置。
圖解
星空效果
參考代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>starts</title>
<style>*{margin: 0; padding: 0;}</style>
</head>
<body>
<canvas id="canvas" style="display: block; background-color: black;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
var WIDTH, HEIGHT
window.onload = function(){
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
WIDTH = document.documentElement.clientWidth
HEIGHT = document.documentElement.clientHeight
canvas.width = WIDTH
canvas.height = HEIGHT
for(var i = 0; i < 100; i ++){
var r = Math.random()*10 + 10,
x = Math.random()*(WIDTH - 2*r) + r,
y = Math.random()*(HEIGHT - 2*r) + r,
a = Math.random()*360
drawStart(context, x, y, r/2, r, a)
}
}
function drawStart(cxt, x, y, r, R, rot = 0){
cxt.beginPath()
for(var i = 0; i < 5; i ++){
cxt.lineTo(Math.cos((18 + i*72 - rot)/180 * Math.PI) * R + x,
-Math.sin((18 + i*72 - rot)/180 * Math.PI) * R + y)
cxt.lineTo(Math.cos((54 + i*72 - rot)/180 * Math.PI) * r + x,
-Math.sin((54 + i*72 - rot)/180 * Math.PI) * r + y)
}
cxt.closePath()
cxt.fillStyle = 'yellow'
cxt.fill()
}
</script>
</body>
</html>
線性漸變
示例代碼
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>linear-gradient</title>
</head>
<body>
<canvas id="canvas" style="display: block; border: 2px solid #ccc; margin: 30px auto 0;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
window.onload = function () {
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
canvas.width = 700
canvas.height = 700
var linearGrad = context.createLinearGradient(0, 0, 700, 700)
linearGrad.addColorStop(0.0, 'red')
linearGrad.addColorStop(0.25, 'yellow')
linearGrad.addColorStop(0.5, 'green')
linearGrad.addColorStop(0.75, 'blue')
linearGrad.addColorStop(1.0, 'coral')
context.fillStyle = linearGrad
context.fillRect(0, 0, 700, 700)
}
</script>
</body>
</html>
徑向漸變
示例代碼
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>radial-gradient</title>
</head>
<body>
<canvas id="canvas" style="display: block; border: 2px solid #ccc; margin: 30px auto 0;">
當前瀏覽器不支持canvas,請更換瀏覽器后再試
</canvas>
<script>
window.onload = function () {
/** @type {HTMLCanvasElement} */
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d')
// 畫布寬高
canvas.width = 700
canvas.height = 700
var radialGrad = context.createRadialGradient(350, 350, 0, 350, 350, 400)
radialGrad.addColorStop(0.0, 'red')
radialGrad.addColorStop(0.25, 'yellow')
radialGrad.addColorStop(0.5, 'green')
radialGrad.addColorStop(0.75, 'blue')
radialGrad.addColorStop(1.0, 'coral')
context.fillStyle = radialGrad
context.fillRect(0, 0, 700, 700)
}
</script>
</body>
</html>
使用圖片、畫布、或者video
createPattern(img, repeat-style)
createPattern(canvas, repeat-style)
createPattern(video, repeat-style)
// repeat-style: no-repeat
// repeat-x
// repeat-x
// repeat-y
// repeat