簡體   English   中英

在HTML畫布上分層和概述

[英]layering and outlining on HTML canvas

我一直在研究看似簡單的圖形。 我希望創建一個圓,並用一條直線將圓連接起來,並用一些背景填充圓。 我幾乎快明白了,但是這一塊讓我震驚了。

我可以定義畫布,創建圓,以及將它們連接起來的直線:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = $(window).width();
canvas.height = $(window).height();

ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 10;

//Create two nodes
ctx.arc( 100, 100, 25, 0, 2*Math.PI);
ctx.moveTo(200+25, 200)
ctx.arc( 200, 200, 25, 0, 2*Math.PI);

//line connecting two nodes
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);

ctx.stroke();

看起來像這樣:

在此處輸入圖片說明

然后,我要做的是用圖像填充圓圈(這就是為什么我使用clip() ),但是為了示例起見,使用白色填充也說明了問題:

//simulate filling in nodes with image, in this case solid color
ctx.clip();
ctx.fillStyle = "white";
ctx.fill();

在此處輸入圖片說明

現在我快到了,但是我看到的有些鋸齒狀的邊緣只是Chrome中的一個小“ bug”,而且我也喜歡圓圈上的黑色粗輪廓。 因此,我只想回顧兩個圓圈並概述它們。 似乎不管我做什么,上下文始終記住連接這兩者的那條線,並且在調用stroke()之后,我最終將連接器線放在圖像的頂部:

//would like to just re-outline circles, not connecting line
ctx.stokeStyle = "black";
ctx.arc( 100, 100, 25, 0, 2*Math.PI);
ctx.moveTo(200+25, 200)
ctx.arc( 200, 200, 25, 0, 2*Math.PI);
ctx.stroke();

在此處輸入圖片說明

我不知道的是如何在填充白色背景(加載圖像)后再次勾勒出兩個圓圈?

我認為它就像分層繪制。 首先,我畫一些線,然后放入圖像,然后再畫在頂部。 不知道html canvas是否打算那樣使用。 謝謝。

JSFiddle示例在這里

您忘記了開始一條新的道路。

每當開始新形狀時,都必須使用ctx.beginPath否則上下文將重繪所有先前的路徑。

順便說一下,鋸齒狀的圓圈是因為您要重新渲染它們,這會導致邊緣變得鋸齒狀。

 var canvas = document.createElement("canvas"); var ctx = canvas.getContext('2d'); canvas.width = 500; canvas.height = 500; document.body.appendChild(canvas); ctx.setTransform(1,0,0,1,0,-50); // just moving everything up to be seen in snippet. ctx.beginPath(); ctx.strokeStyle = "black"; ctx.fillStyle = "#FAFAFF"; ctx.lineWidth = 10; //Create two nodes /* dont draw the two circle the first time as you are doubling the render causing the edges to get to sharp making them appear jaggy. ctx.arc( 100, 100, 25, 0, 2*Math.PI); ctx.moveTo(200+25, 200) ctx.arc( 200, 200, 25, 0, 2*Math.PI); */ //line connecting two nodes ctx.moveTo(100, 100); ctx.lineTo(200, 200); ctx.stroke(); ctx.beginPath(); // start a new path and removes all the previous paths //Create two nodes ctx.arc( 100, 100, 25, 0, 2*Math.PI); ctx.moveTo(200+25, 200) ctx.arc( 200, 200, 25, 0, 2*Math.PI); ctx.fill(); ctx.beginPath(); // start a new path and removes all the previous paths //Create two nodes ctx.arc( 100, 100, 25, 0, 2*Math.PI); ctx.moveTo(200+25, 200) ctx.arc( 200, 200, 25, 0, 2*Math.PI); ctx.stroke(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM