[英]HTML5 Canvas - How to Draw a line over an image background?
我試圖在圖像背景上繪制一條線 - 在HTML5 Canvas中。 但是,總是在圖像后面繪制線條。 實際上,首先繪制線條,然后繪制圖片 - 無論我如何調用函數。
如何將線條置於圖像頂部?
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
drawbackground(canvas, context);
drawlines(canvas, context);
function drawbackground(canvas, context){
var imagePaper = new Image();
imagePaper.onload = function(){
context.drawImage(imagePaper,100, 20, 500,500);
};
imagePaper.src = "images/main_timerand3papers.png";
}
function drawlines(canvas, context){
context.beginPath();
context.moveTo(188, 130);
context.bezierCurveTo(140, 10, 388, 10, 388, 170);
context.lineWidth = 10;
// line color
context.strokeStyle = "black";
context.stroke();
}
完全未經測試的代碼,但你嘗試過類似的東西嗎?
function drawbackground(canvas, context, onload){
var imagePaper = new Image();
imagePaper.onload = function(){
context.drawImage(imagePaper,100, 20, 500,500);
onload(canvas, context);
};
imagePaper.src = "images/main_timerand3papers.png";
}
然后調用這樣的方法......
drawbackground(canvas, context, drawlines);
為了提高效率,假設您要對此行或多行進行多次重繪,則將畫布的CSS background-image
設置為圖像。
<canvas style="background-image:url('images/main_timerand3papers.png');"></canvas>
將您的圖像onload更改為以下內容:
imagePaper.onload = function () {
context.drawImage( imagePaper, 100, 20, 500, 500 );
drawLines( canvas, context );
};
然后確保刪除之前對drawLines
調用。
這個解決方案的重要一點是, onload
函數將在未來的某個時間執行,而drawLines函數會立即執行。 您必須始終小心如何構建回調,尤其是在嵌套回調時。
或者你可以嘗試這個:
drawbackground(canvas, context);
context.globalCompositeOperation = 'destination-atop';
drawlines(canvas, context);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.