2015-09-21 99 views
0

我用,同時對第二階段的movieclip,其中之一在它有一個梯度塊使用這三條線AS3的在Flash中創建一個梯度掩模:什麼是Flash CC for HTML5 Canvas中的等效漸變遮罩?

gradientMask_mc.cacheAsBitmap = true; 
something_mc.cacheAsBitmap = true; 
something_mc.mask = gradientMask_mc; 

現在我與Flash試驗CC的HTML5 Canvas,我似乎無法找到相應的東西。這是一個完全不同的設置或什麼?我的搜索只產生AS3解決方案。請和謝謝!

回答

0

在純HTML5 canvas和javascript中將兩個圖像與漸變混合。

// img1, img2 are the two images 
// ctx is the canvas. 


// setup. Only do this once or when you change the masking 
// create a mask canvas the size of the first image 
var gradImg1Masked = document.createElement("canvas"); 
gradImg1Masked.width = img1.width; // set the width and height 
gradImg1Masked.height = img1.height; 

var ctx1 = gradImg1Masked.getContext("2d",{ alpha: true }); // get the context 

var gradient = ctx1.createLinearGradient(0, 0, 0, img1.height); // create a gradient 
                   // assuming its from 
                   // top to bottom. 

// add colour stops black full opaque at top to full transparent at bottom 
gradient.addColorStop(0, "rgba(0,0,0,1)"); 
gradient.addColorStop(1, "rgba(0,0,0,0)"); 

ctx1.globalAlpha = 1; // ensure alpha is on full 
ctx1.globalCompositeOperation = "source-over"; // ensure correct filter 
ctx1.drawImage(img1, 0, 0); // draw the image on the mask canvas 

ctx1.fillStyle = gradient; // set the fill style 
ctx1.globalCompositeOperation = "destination-in"; // set filter to mask letting 
               // only opaque pixels in 
ctx1.fillRect(0, 0, img1.width, img1.height); // create the masked image 
               // by rendering the gradiant ontop 

// gradImg1Masked is now the masked copy of img1 

這是設置。以下是渲染。

// Rendering the images with the mask 
// simply draw the second image and the the first on top 
// ctx is the render surface you are displaying 
// x and y are where you want the top left of the images to be. 
ctx.globalAlpha = 1; // ensure alpha is on full 
ctx.globalCompositeOperation = "source-over"; // ensure correct filter 

// draw the second image at x,y screen pos 
ctx.drawImage(img2,0,0,img2.width,img2.height,x,y,img2.width,img2.height); 

// draw the masked image ontop using the second image's size 
ctx.drawImage(gradImg1Masked, 
     0, 0, gradImg1Masked.width, gradImg1Masked.height, 
     x, y, img2.width, img2.height); 

希望這會有所幫助。 Flash CC的HTML5 Canvas可能有一個更簡單的方法,但是我發現框架與功能非常強大的HTML5/Javascript相比幾乎沒有什麼優勢,同時混淆了正在發生的事情,並且減慢了一切。他們的使用當然是個人決定。

+0

謝謝!我一定會試試這個! – Tessa

+0

謝謝..幸運的是我看到了您的消息,因爲我剛剛注意到我的代碼中有錯誤。設置漸變停止我在0添加了兩個,現在它是正確的。 – Blindman67

+0

哈哈,不用擔心。原來那個特定的項目被推遲了,因爲另一個項目成爲了更高的優先級,所以我還沒有機會回到它。但一旦我回到它,我一定會讓你知道發生了什麼。 – Tessa