캔버스 요소에서 요소를 그린 후 불투명도 (알파, 투명도)를 변경하는 방법은 무엇입니까?
HTML5 <canvas>
요소를 사용하여 이미지 파일 (PNG, JPEG 등)을로드하고 캔버스에 완전히 투명하게 그린 다음 페이드 인합니다. 이미지를로드하고 이미지를 그리는 방법을 알아 냈습니다. 캔버스, 그러나 그려지는 불투명도를 변경하는 방법을 모르겠습니다.
지금까지 내가 작성한 코드는 다음과 같습니다.
var canvas = document.getElementById('myCanvas');
if (canvas.getContext)
{
var c = canvas.getContext('2d');
c.globalAlpha = 0;
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
}
img.src = 'image.jpg';
}
누군가가 설정하는 속성이나 불투명도를 변경하는 호출하는 함수와 같은 올바른 방향으로 나를 가리켜 주시겠습니까?
필자는 기본 모양으로 칠하고 채우기 및 획을 설정할 수있는 경우이 질문에 대한 답을 찾고 있습니다 (명확하게하기 위해 불투명도로 도형을 그리는 방법과 같이 사용자 정의 불투명도로 이미지를 그릴 수 있기를 원합니다) 알파로 색상을 지정하여 투명도를 정의합니다. 내가 지금까지 결론을 내린 한, 이것은 이미지 드로잉에 영향을 미치지 않는 것 같습니다.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
나는 globalCompositeOperation
이미지로 작품 을 설정한다고 결론 지었다 .
//works with images
ctx.globalCompositeOperation = "lighter";
이미지를 색조하고 쉽게 투명하게 만들 수 있도록 색상을 설정하는 세 번째 방법이 있는지 궁금합니다.
편집하다:
더 파고 난 후에 이미지 globalAlpha
를 그리기 전에 매개 변수 를 설정하여 이미지의 투명도를 설정할 수 있다고 결론을 내 렸습니다 .
//works with images
ctx.globalAlpha = 0.5
시간이 지남에 따라 페이딩 효과를 얻으려면 알파 값을 변경하는 일종의 루프가 필요합니다. 이것은 상당히 쉽습니다.이를 달성하는 한 가지 방법은 setTimeout
함수입니다. 알파를 변경하는 루프를 만드는 방법을 찾으십시오. 시각.
다음을 사용하는 간단한 코드 예 globalAlpha
:
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();
img
로드 해야하는 경우 :
var img = new Image();
img.onload = function() {
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore()
};
img.src = "http://...";
노트:
이미지가 이미 캐시에있는 경우에도 모든 플랫폼에서 핸들러가 호출
'src'
되도록 마지막을 설정하십시오onload
.변경 사항을
globalAlpha
asave
와 같은 항목으로 래핑 하고restore
(실제로 많이 사용) 특히 드로잉 코드 비트가 이벤트에서 호출 될 때 다른 곳에서 설정을 방해하지 않도록합니다.
편집하다: "정답"으로 표시된 답변이 올바르지 않습니다.
It's easy to do. Try this code, swapping out "ie.jpg" with whatever picture you have handy:
<!DOCTYPE HTML>
<html>
<head>
<script>
var canvas;
var context;
var ga = 0.0;
var timerId = 0;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
timerId = setInterval("fadeIn()", 100);
}
function fadeIn()
{
context.clearRect(0,0, canvas.width,canvas.height);
context.globalAlpha = ga;
var ie = new Image();
ie.onload = function()
{
context.drawImage(ie, 0, 0, 100, 100);
};
ie.src = "ie.jpg";
ga = ga + 0.1;
if (ga > 1.0)
{
goingUp = false;
clearInterval(timerId);
}
}
</script>
</head>
<body onload="init()">
<canvas height="200" width="300" id="myCanvas"></canvas>
</body>
</html>
The key is the globalAlpha property.
Tested with IE 9, FF 5, Safari 5, and Chrome 12 on Win7.
The post is old so far I'll go with my suggestion. Suggestion is based on pixel manipulation in canvas 2d context. From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData and putImageData
getImageData function usage:
var myImageData = context.getImageData(left, top, width, height);
and putImageData syntax:
context.putImageData(myImageData, dx, dy); //dx, dy - x and y offset on your canvas
Where context is your canvas 2d context
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x is x offset, y is y offset on canvas
So we having code making image half-transparent
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).
// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';
I think this answers the question best, it actually changes the alpha value of something that has been drawn already. Maybe this wasn't part of the api when this question was asked.
given 2d context c
.
function reduceAlpha(x, y, w, h, dA) {
var screenData = c.getImageData(x, y, w, h);
for(let i = 3; i < screenData.data.length; i+=4){
screenData.data[i] -= dA; //delta-Alpha
}
c.putImageData(screenData, x, y );
}
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.
'Programing' 카테고리의 다른 글
MYSQL 업데이트 명령문 내부 조인 테이블 (0) | 2020.05.16 |
---|---|
JavaScript / JQuery를 사용하여 간단한지도를 만드는 방법 (0) | 2020.05.16 |
안드로이드 APK의 패키지 이름을 읽으십시오 (0) | 2020.05.16 |
Android API 21 툴바 패딩 (0) | 2020.05.16 |
ASP.NET Core의 .json 파일에서 AppSettings 값을 읽는 방법 (0) | 2020.05.16 |