Reputation: 7324
I am using the canvas control. I load an image into it:
var cn1 = document.getElementById('canvas1');
cn1.addEventListener("mousedown", getPosition, false);
var context = cn1.getContext('2d');
var width = 360;
var height = 240
cn1.width = 360;
cn1.height = 240;
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0, width, height);
DrawLines();
};
imageObj.src = '/Images/7.jpg';
I then overlay some grid lines using:
function DrawLines()
{
context.beginPath();
for (var x = 0; x < 361; x = x + 24) {
context.moveTo(x, 0);
context.lineTo(x, 0);
context.lineTo(x, 240);
}
for (var y = 0; y < 241; y = y + 24) {
context.moveTo(0, y);
context.lineTo(0, y);
context.lineTo(360, y);
}
context.lineWidth = 1;
context.strokeStyle = '#FC5C5C';
context.stroke();
context.closePath();
}
Which gives me this look:
I then, after clicking a cell want to overlay with a blue color with its alpha transparency set so the User can still see the original image.
The mock up for this looks like:
I can handle the click event. What I need is the JavaScript to overlay with my semi-transparent blue color.
I found this on StackOverFlow:
// Loops through all of the pixels and modifies the components.
for (var i = 0, n = pix.length; i <n; i += 4) {
pix[i] = uniqueColor[0]; // Red component
pix[i+1] = uniqueColor[1]; // Green component
pix[i+2] = uniqueColor[2]; // Blue component
//pix[i+3] is the transparency.
}
ctx.putImageData(imgd, 0, 0);
From this link:Another example but this would not give me what I want. How can I achieve what I want?
thanks
Upvotes: 0
Views: 1384
Reputation:
Just set fillStyle
to a transparent color using rgba()
, then fillRect()
with that style set.
Using getImageData
/putImageData
is possible, but is slower and it requires CORS to be fulfilled in case image is loaded from a different origin than the page.
Here is what you can do:
context.fillStyle = "rgba(150,150,255, 0.3)"; // last value is alpha [0.0, 1.0]
context.fillRect(x, y, w, h);
Tip: you can also reduce the grid line code to:
context.moveTo(x, 0);
//context.lineTo(x, 0); not needed here
context.lineTo(x, 240);
Upvotes: 2
Reputation: 91
You want to use, instead of say #ccccff
for the fillStyle
, use rgba(100, 100, 255, 0.5)
, where the last number is the alpha, or opacity. It's represented as a decimal, to represent percentage; so in this case, that's 50% opacity.
Upvotes: 1