Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
、什么是Canvas?
HTML5 提供Canvas API,其本質上是一個DOM元素,可以看成是瀏覽器提供一塊畫布供我們在上面渲染2D或者3D圖形。由于3D繪制上下文(webgl)目前在很多瀏覽器上兼容性較差,所以我們一般用于繪制2D圖形。
<canvas id="canvas"></canvas>
2、為什么使用Canvas?
Canvas是HTML5引入的標簽,在此之前我們通常會使用SVG來繪制一些圖形,那么兩者之間有什么區別呢?SVG可縮放矢量圖形(Scalable Vector Graphics)是基于可擴展標記語言XML描述的2D圖形的語言,兩者部分區別:
由于Canvas是通過Javascript來完成繪制的,所以可控性很強,我們可以比較精確的控制圖形渲染的每一幀;從另一方面來說,如果在高頻率渲染中要處理過多的DOM元素就意味著性能一定不會太好,渲染速度會下降很多。Canvas的高性能能夠保障復雜場景中圖形的渲染效率,所以目前很多領域都會使用Canvas,例如動畫、游戲圖形、數據可視化、照片處理和實時視頻處理等。
3、Canvas的基本使用
要使用Canvas,我們需要先獲取Canvas元素的引用繼而通過getContext()方法獲取圖形的繪制上下文。
const canvas=document.getElementById('canvas')
const ctx=canvas.getContext('2d')
獲取到圖形繪制上下文后,我們就能使用CanvasRenderingContext2D接口上的繪圖API了,接下來我們可以了解一些比較常規的使用。
3.1、畫布屬性:
ctx.width=300
ctx.height=300
ctx.fillStyle='#fff'
ctx.strokeStyle='blue'
ctx.lineWidth=5
ctx.globalAlpha=0.3
ctx.globalCompositeOperation='destination-out' // 新老圖形重疊部分變透明
......
3.2、繪制圖形:
ctx.fillStyle='red'
ctx.fillRect(100,100,100,100)
ctx.strokeStyle='blue'
ctx.strokeRect(200,200,100,100)
ctx.clearRect(125,125,50,50)
ctx.strokeRect(130,130,40,40)
3.3、繪制路徑:
ctx.beginPath()
ctx.moveTo(50,50)
ctx.lineTo(100,100)
ctx.lineTo(100,0)
ctx.fill()
ctx.beginPath()
ctx.moveTo(110,100)
ctx.lineTo(150,100)
ctx.lineTo(150,200)
ctx.lineTo(110,200)
ctx.closePath() // 輪廓圖形不會根據從當前坐標到起始坐標生成輪廓,所以需要閉合路徑
ctx.stroke()
3.4、繪制圓弧:
注意:arc函數中的角度的單位是弧度而不是度,弧度=(Math.PI/180)*度
// 圓左上部分
ctx.beginPath()
ctx.arc(100,100,50,Math.PI,Math.PI*3/2,false)
ctx.strokeStyle='#ff6700'
ctx.stroke()
// 圓右上部分
ctx.beginPath()
ctx.arc(100,100,50,Math.PI*3/2,0,false)
ctx.strokeStyle='#6700ff'
ctx.stroke()
// 圓右下部分
ctx.beginPath()
ctx.arc(100,100,50,0,Math.PI/2,false)
ctx.strokeStyle='#00FFFF'
ctx.stroke()
// 圓左下部分
ctx.beginPath()
ctx.arc(100,100,50,Math.PI/2,Math.PI,false)
ctx.strokeStyle='#8B008B'
ctx.stroke()
// 兩條切線的交點坐標為(0,0)
ctx.beginPath()
ctx.moveTo(100,0)
ctx.arcTo(0,0,0,100,100)
ctx.fillStyle='blue'
ctx.fill()
3.5、漸變對象:
創建好漸變對象之后,可以通過漸變對象上的.addColorStop(offset,color)為每一個漸變階段填充顏色,offset為0-1的偏移值。
const gradient=ctx.createLinearGradient(50, 50, 250, 50)
gradient.addColorStop(0, 'blue')
gradient.addColorStop(0.5, 'green')
gradient.addColorStop(1, 'red')
ctx.fillStyle=gradient
ctx.fillRect(0, 0, 300, 90)
const radialGradient=ctx.createRadialGradient(200,200,100,200,200,50);
radialGradient.addColorStop(0,"yellow");
radialGradient.addColorStop(1,"green");
ctx.fillStyle=radialGradient;
ctx.fillRect(100,100,200,200);
3.6、像素操作:
const div=document.querySelector('div')
let mousedown=false;
function getRandom() {
return Math.round(255 * Math.random());
}
function getColor() {
return `rgb(${getRandom()},${getRandom()},${getRandom()})`;
}
const gradient=ctx.createLinearGradient(0, 0, 300, 300);
gradient.addColorStop(0, getColor());
gradient.addColorStop(0.6, getColor());
gradient.addColorStop(1, getColor());
function clear() {
ctx.fillStyle=gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.beginPath();
ctx.fillStyle=gradient;
ctx.fillRect(0, 0, 300, 300);
function selector(x=150, y=150) {
clear();
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.strokeStyle="#fff";
ctx.stroke();
const { data }=ctx.getImageData(x, y, 1, 1); // 獲取(x,y)點對應的imageData
const color=`rgba(${data[0]},${data[1]},${data[2]},${data[3] / 255})`
div.innerText=`color: ${color}`;
div.style.backgroundColor=color
}
function handleSelector(e) {
const x=e.offsetX;
const y=e.offsetY;
selector(x, y);
}
canvas.addEventListener("mousedown", (e)=> {
mousedown=true;
handleSelector(e)
});
canvas.addEventListener("mouseup", ()=> {
mousedown=false;
});
canvas.addEventListener("mousemove", (e)=> {
if (mousedown) {
handleSelector(e)
}
});
selector();
3.7、畫布狀態:
當我們需要通過空間轉換來繪制圖形時,保存與恢復畫布的狀態是很關鍵的,因為我們是在同一塊畫布上繪制圖形,而變換都是基于畫布的,這與我們平時使用到的CSS 2D轉換截然不同,所以我們在下一步繪制時要確認此時畫布的狀態是否是我們的理想狀態。
ctx.save() // 保存畫布初始狀態
ctx.translate(100,100) // 將畫布原點轉移至(100,100)
ctx.fillStyle='red'
ctx.fillRect(0,0,50,50)
ctx.restore() // 恢復畫布狀態,此時畫布原點為(0,0)
ctx.fillStyle='blue'
ctx.fillRect(0,0,50,50)
3.8、幾何變化:
const colors=['red','orange','yellow','green','blue','purple'];
ctx.translate(150,150)
for(let i=0; i < 6; i++) {
ctx.beginPath()
ctx.fillStyle=colors[i]
ctx.moveTo(0,0)
ctx.lineTo(100,0)
ctx.lineTo(100,50)
ctx.rotate(Math.PI/3)
ctx.fill()
}
4、綜合實戰
const p=Math.PI;
function clock() {
const date=new Date();
const hour=date.getHours()
const s=date.getSeconds();
const m=date.getMinutes();
const h=!!(hour % 12) ? hour % 12 : 12;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save(); // 保存畫布初始狀態
ctx.translate(150, 150);
ctx.rotate(-p / 2);
// 輪廓
ctx.beginPath();
ctx.lineWidth=5;
ctx.strokeStyle="#76b2ff";
ctx.arc(0, 0, 80, 0, p * 2);
ctx.stroke();
// 圓心
ctx.beginPath();
ctx.arc(0, 0, 2, 0, p * 2);
ctx.fill();
// 分針、秒針刻度
for (let i=0; i < 60; i++) {
ctx.beginPath();
ctx.rotate(p / 30);
ctx.moveTo(75, 0);
ctx.lineWidth=4;
ctx.strokeStyle="#89f086";
ctx.lineTo(80, 0);
ctx.stroke();
}
// 時針刻度
for (let i=0; i < 12; i++) {
ctx.beginPath()
ctx.rotate(p / 6)
ctx.moveTo(70, 0)
ctx.lineTo(80, 0)
ctx.stroke()
}
ctx.save(); // 保存畫布變換之后的狀態
// 秒針
ctx.beginPath();
ctx.rotate(s * (p / 30));
ctx.lineWidth=2
ctx.strokeStyle='#ff6700'
ctx.moveTo(0, 0);
ctx.lineTo(80, 0);
ctx.stroke();
// 恢復之前的狀態再保存,時針、分針、秒針都是基于原點以及畫布方向變換后繪制
ctx.restore();
ctx.save();
// 分針
ctx.beginPath();
ctx.rotate(m * (p / 30));
ctx.lineWidth=3;
ctx.strokeStyle='#6700ff'
ctx.moveTo(0, 0);
ctx.lineTo(70, 0);
ctx.stroke();
ctx.restore();
// 時針
ctx.beginPath();
ctx.rotate(h * (p / 6));
ctx.lineWidth=4;
ctx.moveTo(0, 0);
ctx.lineTo(60, 0);
ctx.stroke();
ctx.restore(); // 恢復畫布最初狀態
document.querySelector('div').innerText=`Now:${h} : ${m} : ${s} ${hour > 12 ? 'pm' : 'am'}`
window.requestAnimationFrame(clock);
}
clock();
5、小結
隨著互聯網的高速發展,用戶對頁面的視覺和交互有著越來越高的要求,傳統的web開發無法得到滿足,利用Canvas強大的繪圖能力,可以讓網頁顯示的內容更加的豐富多彩,也能給用戶帶來更好的視覺體驗。
作者:LLS-FE團隊
來源:微信公眾號:流利說技術團隊
出處:https://mp.weixin.qq.com/s/bvkx3wOeMvIUU64cktX6iA
TML5 Canvas是HTML5新增的一個元素,它提供了一個可執行JavaScript腳本繪制圖形的區域。Canvas元素通過使用JavaScript API,可以在瀏覽器上繪制圖形、渲染動畫和實現交互效果等。
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas示例</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// 獲取Canvas元素和繪圖上下文
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
// 繪制矩形
ctx.fillStyle="blue";
ctx.fillRect(50, 50, 100, 100);
// 繪制圓形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle="red";
ctx.fill();
</script>
</body>
</html>
在上述代碼中,我們首先獲取了Canvas元素和繪圖上下文(Context),然后使用fillRect()方法繪制了一個藍色的矩形,使用arc()方法繪制了一個紅色的圓形。最后,我們使用fill()方法填充了圓形的顏色。
載說明:原創不易,未經授權,謝絕任何形式的轉載
使用HTML5 Canvas構建繪圖應用是在Web瀏覽器中創建交互式和動態繪圖體驗的絕佳方式。HTML5 Canvas元素提供了一個繪圖表面,允許您操作像素并以編程方式創建各種形狀和圖形。本文將為您提供使用HTML5 Canvas創建繪圖應用的概述和指導。此外,它還將通過解釋HTML設置、JavaScript實現、用戶交互和繪圖功能來幫助您理解構建繪圖應用的步驟。
HTML canvas標簽是一個HTML元素,它提供了一個空白的繪圖表面,可以使用JavaScript來渲染圖形、形狀和圖像。繪圖應用程序利用HTML5 canvas的功能,使用戶能夠以數字方式創建藝術作品、草圖和插圖。此外,使用HTML5 canvas構建的繪圖應用程序允許用戶與畫布進行交互,捕捉鼠標移動和點擊事件,實時繪制、擦除或操作元素。
HTML5畫布非常適合創建繪圖應用程序,原因如下:
您可以使用HTML5 Canvas以以下方式為繪圖應用程序設置HTML結構:
<!DOCTYPE html>
<html>
<head>
<title>Drawing Application</title>
<style>
body {
margin: 3px;
padding: 6px;
font-size: 22px;
}
canvas {
border: 2px solid black;
}
.toolbar button,
#clearButton,
#saveButton {
padding: 15px;
font-size: 24px;
}
</style>
</head>
<body>
<h1>HTML Setup for a Drawing Application Using HTML5 Canvas</h1>
<canvas id="myCanvas" width="700" height="400"></canvas>
<button id="clearButton">Clear</button>
</body>
</html>
結果:
在上面的示例中,我們通過添加帶有ID為“myCanvas”的畫布元素并分別指定其寬度和高度為700和400像素來構建了繪圖應用程序的HTML結構。我們還在畫布下方包含了一個ID為“clearButton”的“清除”按鈕,為用戶提供了一種方便的方式來從畫布中刪除所有繪制的元素,并為新的繪圖創建一個空白畫布。
添加一些元素和功能,使用額外的HTML和CSS使繪圖應用程序看起來更像一個應用程序。例如,您可以添加一個工具欄、一個顏色調色板、一個畫筆大小和一個狀態欄。以下是一個示例,其中包含一些額外的元素,以增強繪圖應用程序的外觀和布局:
<div class="toolbar">
<button id="pencilTool">Pencil</button>
<button id="brushTool">Brush</button>
<button id="eraserTool">Eraser</button>
<input type="color" id="colorPicker" />
<select id="brushSize">
<option value="1">1px</option>
<option value="3">3px</option>
<option value="5">5px</option>
</select>
</div>
<div class="color-palette">
<div class="color-swatch" style="background-color: black"></div>
<div class="color-swatch" style="background-color: red"></div>
<div class="color-swatch" style="background-color: green"></div>
<div class="color-swatch" style="background-color: blue"></div>
</div>
使用CSS進行樣式設置:
.toolbar {
margin-bottom: 12px;
}
.toolbar button {
padding: 10px;
margin-right: 7px;
background: white;
color: black;
border: none;
cursor: pointer;
}
.color-palette {
display: flex;
justify-content: center;
margin-bottom: 12px;
}
.color-palette .color-swatch {
width: 32px;
height: 32px;
border: 3px solid white;
cursor: pointer;
margin-right: 6px;
}
.status-bar {
padding: 7px;
background: white;
color: black;
}
結果:
上面的例子包括了創建繪圖應用所需的結構和樣式,包括工具欄(帶有不同工具的按鈕,如鉛筆、畫筆、橡皮擦)、顏色調色板、畫筆大小選擇下拉菜單、繪圖畫布、狀態欄和清除按鈕。您可以根據所需的功能自定義這些元素。
沒有JavaScript功能,上述示例中的按鈕、顏色樣本和清除按鈕將不會執行任何操作。要使用繪圖應用程序,您必須添加相應的JavaScript源代碼來處理功能和與畫布元素的交互。以下是您可以使用JavaScript處理畫布元素功能和交互的幾種方式:
const canvas=document.getElementById("myCanvas");
const context=canvas.getContext("2d");
const canvas=document.getElementById("myCanvas");
const ctx=canvas.getContext("2d");
let isDrawing=false;
let selectedTool="pencil";
function startDrawing(event) {
isDrawing=true;
draw(event);
}
function draw(event) {
if (!isDrawing) return;
const x=event.clientX - canvas.offsetLeft;
const y=event.clientY - canvas.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
}
function stopDrawing() {
isDrawing=false;
ctx.beginPath();
}
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
const clearButton=document.getElementById("clearButton");
clearButton.addEventListener("click", function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
const colorSwatches=document.querySelectorAll(".color-swatch");
colorSwatches.forEach((swatch)=> {
swatch.addEventListener("click", function() {
const color=this.style.backgroundColor;
ctx.strokeStyle=color;
});
});
const brushSizeSelect=document.getElementById("brushSize");
brushSizeSelect.addEventListener("change", function() {
const brushSize=this.value;
ctx.lineWidth=brushSize;
});
const pencilToolButton=document.getElementById("pencilTool");
pencilToolButton.addEventListener("mousedown", function() {
selectedTool="pencil";
ctx.globalCompositeOperation="source-over";
});
const brushToolButton=document.getElementById("brushTool");
brushToolButton.addEventListener("mousedown", function() {
selectedTool="brush";
ctx.globalCompositeOperation="multiply";
});
const eraserToolButton=document.getElementById("eraserTool");
eraserToolButton.addEventListener("mousedown", function() {
selectedTool="eraser";
ctx.globalCompositeOperation="destination-out";
});
const colorPicker=document.getElementById("colorPicker");
colorPicker.addEventListener("input", function() {
const color=this.value;
ctx.strokeStyle=color;
});
結果:
在上面的示例中,繪圖應用程序的功能被激活,您可以輕松地使用它來繪制您想要的內容。請注意,現在所有的元素都在正常工作,您可以在畫布上繪制,選擇不同的繪圖工具(鉛筆、畫筆、橡皮擦),選擇顏色,調整畫筆大小,并清除畫布。
JavaScript代碼指定了HTML文檔中的畫布元素,獲取了2D繪圖上下文,并在HTML文檔的各個元素上設置了事件監聽器,例如畫布、按鈕、顏色樣本和輸入字段。這些事件監聽器響應用戶的鼠標點擊、移動和值變化等操作。當觸發時,相應的JavaScript函數根據用戶的操作修改畫布繪圖上下文(ctx)。
它從HTML文檔中選擇清除按鈕并添加一個點擊事件監聽器。當點擊時,它使用2D繪圖上下文的clearRect方法清除整個畫布。例如,當您在畫布上點擊并拖動鼠標時,將調用 startDrawing 、 draw 和 stopDrawing 函數,這些函數跟蹤鼠標坐標并在畫布上繪制線條。
一款繪圖應用程序允許您使用上述工具和功能創建數字藝術作品。它為用戶提供了一個畫布,可以繪制、繪畫和應用不同的效果,以創建視覺組合。繪圖應用程序被藝術家、設計師、愛好者和任何對通過創建視覺吸引人的插圖、繪畫、素描和其他數字藝術形式來表達創造力感興趣的人使用。
將HTML5畫布繪制保存為圖像文件可幫助您與他人分享繪畫或在其他應用程序中使用。用戶可以將繪畫存儲在本地設備上,或通過提供將其保存為圖像文件的選項,將其上傳到各種平臺,如社交媒體、網站或在線畫廊。
此外,保存繪畫使用戶能夠稍后重新訪問和展示他們的創作,增強了繪畫應用程序的可用性和價值。以下是如何將HTML5畫布繪制保存為圖像文件的方法:使用JavaScript,您可以將畫布繪制保存為圖像文件。使用畫布元素的 toDataURL() 方法。該方法將畫布內容轉換為數據URL,可用于創建圖像文件。例如:
<button id="saveButton">Save</button>
const canvas=document.getElementById('myCanvas');
const link=document.createElement('a');
function saveCanvasAsImage() {
const dataURL=canvas.toDataURL('image/png');
link.href=dataURL;
link.download='drawing.png';
link.click();
}
saveCanvasAsImage();
在上面的示例中,添加了一個具有id“saveButton”的新按鈕元素,并添加了一個點擊事件監聽器。當您點擊“保存”按鈕時,它會觸發一個函數,該函數使用 toDataURL() 來檢索畫布的數據URL。然后,它創建一個動態生成的鏈接元素,將數據URL設置為href屬性,并使用download屬性指定所需的文件名為“drawing.png”,以啟動圖像文件下載。
該方法支持不同的圖像格式,如PNG、JPEG和GIF。您可以通過修改所需文件的類型(例如JPEG格式的'image/jpeg')來更改格式。保存后,您可以通過電子郵件、消息應用程序或社交媒體平臺分享圖像文件。
利用HTML5畫布的繪圖應用為藝術家、設計師、教育工作者和所有具有創造力的人打開了無限的可能性。無論是作為獨立工具還是集成到其他應用程序中,繪圖應用都賦予用戶表達創造力、與他人分享作品和探索視覺表達的新領域的能力。憑借其豐富的功能,繪圖應用在藝術創作中繼續激發和取悅用戶。所以拿起你的數字畫筆,在可能性的畫布上盡情釋放你的想象力吧!
由于文章內容篇幅有限,今天的內容就分享到這里,文章結尾,我想提醒您,文章的創作不易,如果您喜歡我的分享,請別忘了點贊和轉發,讓更多有需要的人看到。同時,如果您想獲取更多前端技術的知識,歡迎關注我,您的支持將是我分享最大的動力。我會持續輸出更多內容,敬請期待。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。