How can I achieve a blur behind a transparent box (fillStyle = 'rgba(255, 255, 255, 0.2)') in JavaScript canvas? Here's what I've got so far:
var canvas = document.getElementById('draw');
var c = canvas.getContext('2d');
function main() {
c.fillStyle = '#222';
c.fillRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#000';
c.fillRect(32, 32, 64, 64);
c.fillStyle = 'rgba(255, 255, 255, 0.2)';
c.filter = 'blur(5px)';
c.fillRect(16, 16, 128, 24);
}
But what happens, is instead of blurring the background behind the rectangle, is the rectangle itself is blurred, kind of obviously.
In the final script, I will probably use paths instead of rects.
Context2D filters will be applied only on your new drawings, so to also blur the background, you would actually have to redraw the part of the background you want to be blurred.
Fortunately, canvas can drawImage itself.
var blurredRect = {
x: 80,
y: 80,
height: 200,
width: 200,
spread: 10
};
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = draw;
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
function draw() {
canvas.width = img.width / 2;
canvas.height = img.height / 2;
// first pass draw everything
ctx.drawImage(img, 0,0, canvas.width, canvas.height);
// next drawings will be blurred
ctx.filter = 'blur('+ blurredRect.spread +'px)';
// draw the canvas over itself, cropping to our required rect
ctx.drawImage(canvas,
blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height,
blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height
);
// draw the coloring (white-ish) layer, without blur
ctx.filter = 'none'; // remove filter
ctx.fillStyle = 'rgba(255,255,255,0.2)';
ctx.fillRect(blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height);
}
<canvas id="canvas"></canvas>
But, canvas blur filter is a bit different than CSS one in that it will make the spreading stay inside the drawn area. This means that in our case, we have a 5px border around our rectangle that is less blurred than the center.
To workaround, we can take the whole thing in a different order and play with globalCompositeOperation property*:
var blurredRect = {
x: 80,
y: 80,
height: 200,
width: 200,
spread: 10
};
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = draw;
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
function draw() {
var spread = blurredRect.spread,
ratio = 0.5,
// make our blurred rect spreads
x = blurredRect.x - spread,
y = blurredRect.y - spread,
w = blurredRect.width + (spread * 2),
h = blurredRect.height + (spread * 2);
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
// this time we will first draw the blurred rect
ctx.filter = 'blur('+ spread +'px)';
// this time we draw from the img directly
ctx.drawImage(img,
x / ratio, y / ratio, w / ratio, h / ratio,
x, y, w, h
);
// now we will want to crop the resulting blurred image to the required one, so we get a clear-cut
ctx.filter = 'none'; // remove filter
// with this mode, previous drawings will be kept where new drawings are made
ctx.globalCompositeOperation = 'destination-in';
ctx.fillStyle = '#000'; // make it opaque
ctx.rect(blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height);
ctx.fill(); // clear-cut done
// reuse our rect to make the white-ish overlay
ctx.fillStyle = 'rgba(255,255,255,0.2)';
// reset gCO to its default
ctx.globalCompositeOperation = 'source-over';
ctx.fill();
// now we will draw behind the our blurred rect
ctx.globalCompositeOperation = 'destination-over';
ctx.drawImage(img, 0,0, canvas.width, canvas.height);
// reset to defaults
ctx.globalCompositeOperation = 'source-over';
}
<canvas id="canvas"></canvas>
But this approach requires that we keep access to the whole background as a drawable thing, in the example above that was just an image, but in real life, this might mean you'd have to do this operation on a second offscreen canvas.
var blurredRect = {
x: 80,
y: 80,
height: 200,
width: 200,
spread: 2
};
var ctx = canvas.getContext('2d');
// create an off-screen canvas
var bCanvas = canvas.cloneNode();
var bCtx = bCanvas.getContext('2d');
var img = new Image();
img.onload = draw;
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
function draw() {
var spread = blurredRect.spread;
canvas.width = bCanvas.width = img.width / 2;
canvas.height = bCanvas.height = img.height / 2;
// now we have a composed background
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
ctx.font = '40px Impact';
ctx.fillStyle = 'white';
ctx.fillText('..SO BLUR ME..', 120, 282);
// make our clear-cut on the offscreen canvas
bCtx.filter = 'blur(' + spread +'px)';
bCtx.drawImage(canvas,
blurredRect.x - spread, blurredRect.y - spread, blurredRect.width + spread * 2, blurredRect.height + spread * 2,
blurredRect.x - spread, blurredRect.y - spread, blurredRect.width + spread * 2, blurredRect.height + spread * 2
);
// clear-cut
bCtx.filter = 'none';
bCtx.globalCompositeOperation = 'destination-in';
bCtx.beginPath();
bCtx.rect(blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height);
bCtx.fillStyle = '#000';
bCtx.fill();
// white-ish layer
bCtx.globalCompositeOperation = 'source-over';
bCtx.fillStyle = 'rgba(255,255,255,0.2)';
bCtx.fillRect(blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height);
// now just redraw on the visible canvas
ctx.drawImage(bCanvas, 0,0);
}
<canvas id="canvas"></canvas>
*One may say that instead of an offscreen canvas and gCO we could have used ctx.clip(), but since you said it might a more complex Path than a rect, I will not advise to do so. Indeed, while it would require less code, and maybe use less memory, clipping is just bad with antialiasing, and since you are doing blurring, that will just look plain ugly.
Related
I have an issue with the painting context.stokeText that style contains an alpha. A big value of line width makes some effect of intersected strokes, as a result, the color is darker.
How I can avoid this?
ctx.strokeStyle ="rgba(0,0,0,0.3)";
ctx.lineWidth = 15;
ctx.lineJoin="round";
ctx.strokeText(text, x, y);
Image
That's a bit of an inconsistency in the specs since usually overlapping sub-pathes are painted only once.
However strokeText() does create one shape per glyph, and thus this method will indeed paint each glyphs on their own, creating this visible overlapping.
To overcome this, you'll to be a bit creative:
first draw your text fully opaque,
then redraw the produced pixels with the desired alpha level (many ways to do so).
draw that on your scene (or draw the background behind).
Here are a few ways (there are many others):
Probably the easiest, but which costs more memory: use a second disconnected canvas:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
// create a new canvas just for the text
const canvas2 = canvas.cloneNode();
const ctx2 = canvas2.getContext("2d");
ctx2.font = "60px sans-serif";
const text = "MY TEXT";
const x = canvas.width - ctx2.measureText(text).width - 20;
const y = canvas.height - 20;
// draw it fully opaque
ctx2.lineWidth = 15;
ctx2.lineJoin="round";
ctx2.strokeText(text, x, y);
// draw the background on the visible canvas
ctx.fillStyle = "#ffe97f";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// now draw our text canvas onto the visible one
// with the desired opacity
ctx.globalAlpha = 0.3;
ctx.drawImage(canvas2, 0, 0);
<canvas width="465" height="234"></canvas>
More memory friendly, but which requires you to rewrite your drawing logic in a different direction, use compositing:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "60px sans-serif";
const text = "MY TEXT";
const x = canvas.width - ctx.measureText(text).width - 20;
const y = canvas.height - 20;
// first draw the text fully opaque
ctx.lineWidth = 15;
ctx.lineJoin="round";
ctx.strokeText(text, x, y);
// now apply the opacity
ctx.fillStyle ="rgba(0,0,0,0.3)";
ctx.globalCompositeOperation = "source-in";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// and the background
ctx.fillStyle = "#ffe97f";
ctx.globalCompositeOperation = "destination-over";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// if you want to keep drawing "normaly"
ctx.globalCompositeOperation = "source-over";
<canvas width="465" height="234"></canvas>
A mix of both, with different compositing rules:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "60px sans-serif";
const text = "MY TEXT";
const x = canvas.width - ctx.measureText(text).width - 20;
const y = canvas.height - 20;
// first draw the text fully opaque
ctx.lineWidth = 15;
ctx.lineJoin="round";
ctx.strokeText(text, x, y);
// now redraw over itself with the desired opacity
ctx.globalAlpha = 0.3;
ctx.globalCompositeOperation = "copy";
ctx.drawImage(canvas, 0, 0);
ctx.globalAlpha = 1;
// and the background
ctx.fillStyle = "#ffe97f";
ctx.globalCompositeOperation = "destination-over";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// if you want to keep drawing "normaly"
ctx.globalCompositeOperation = "source-over";
<canvas width="465" height="234"></canvas>
I want to change the background color of this image while keeping the form, the effects and the contour of
the image.
<canvas id="canvas01" width="1200" height="800"></canvas>
<script>
function drawImage(imageObj,x, y, width, height){
var canvas = document.getElementById('canvas01');
var context = canvas.getContext('2d');
context.drawImage(imageObj, x, y, width, height);
}
var image = new Image();
image.onload = function(){
drawImage(this, 400, 100, 320, 450);
};
image.src ="images/658FFBC6.png";
</script>
Luma preservation
At the risk of looking similar to the existing answer, I would like to point out a small but important difference using a slightly different approach.
The key is to preserve the luma component in an image (ie. shadow details, wrinkles etc. in this case) so two steps are needed to control the look using blending modes via globalCompositeOperation (or alternatively, a manual approach using conversion between RGB and the HSL color-space if older browsers must be supported):
"saturation": will alter the chroma (intensity, saturation) from the next drawn element and apply it to the existing content on the canvas, but preserve luma and hue.
"hue": will grab the chroma and luma from the source but alter the hue, or color if you will, based on the next drawn element.
As these are blending modes (ignoring the alpha channel) we will also need to clip the result using composition as a last step.
The color blending mode can be used too but it will alter luma which may or may not be desirable. The difference can be subtle in many cases, but also very obvious depending on target chroma and hue where luma/shadow definition is lost.
So, to achieve a good quality result preserving both luma and chroma, these are more or less the main steps (assumes an empty canvas):
// step 1: draw in original image
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, 0, 0);
// step 2: adjust saturation (chroma, intensity)
ctx.globalCompositeOperation = "saturation";
ctx.fillStyle = "hsl(0," + sat + "%, 50%)"; // hue doesn't matter here
ctx.fillRect(0, 0);
// step 3: adjust hue, preserve luma and chroma
ctx.globalCompositeOperation = "hue";
ctx.fillStyle = "hsl(" + hue + ",1%, 50%)"; // sat must be > 0, otherwise won't matter
ctx.fillRect(0, 0, c.width, c.height);
// step 4: in our case, we need to clip as we filled the entire area
ctx.globalCompositeOperation = "destination-in";
ctx.drawImage(img, 0, 0);
// step 5: reset comp mode to default
ctx.globalCompositeOperation = "source-over";
50% lightness (L) will keep the original luma value.
Live Example
Click the checkbox to see the effect on the result. Then test with different chroma and hue settings.
var ctx = c.getContext("2d");
var img = new Image(); img.onload = demo; img.src = "//i.stack.imgur.com/Kk1qd.png";
function demo() {c.width = this.width>>1; c.height = this.height>>1; render()}
function render() {
var hue = +rHue.value, sat = +rSat.value, l = +rL.value;
ctx.clearRect(0, 0, c.width, c.height);
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, 0, 0, c.width, c.height);
if (!!cColor.checked) {
// use color blending mode
ctx.globalCompositeOperation = "color";
ctx.fillStyle = "hsl(" + hue + "," + sat + "%, 50%)";
ctx.fillRect(0, 0, c.width, c.height);
}
else {
// adjust "lightness"
ctx.globalCompositeOperation = l < 100 ? "color-burn" : "color-dodge";
// for common slider, to produce a valid value for both directions
l = l >= 100 ? l - 100 : 100 - (100 - l);
ctx.fillStyle = "hsl(0, 50%, " + l + "%)";
ctx.fillRect(0, 0, c.width, c.height);
// adjust saturation
ctx.globalCompositeOperation = "saturation";
ctx.fillStyle = "hsl(0," + sat + "%, 50%)";
ctx.fillRect(0, 0, c.width, c.height);
// adjust hue
ctx.globalCompositeOperation = "hue";
ctx.fillStyle = "hsl(" + hue + ",1%, 50%)";
ctx.fillRect(0, 0, c.width, c.height);
}
// clip
ctx.globalCompositeOperation = "destination-in";
ctx.drawImage(img, 0, 0, c.width, c.height);
// reset comp. mode to default
ctx.globalCompositeOperation = "source-over";
}
rHue.oninput = rSat.oninput = rL.oninput = cColor.onchange = render;
body {font:16px sans-serif}
<div>
<label>Hue: <input type=range id=rHue max=359 value=0></label>
<label>Saturation: <input type=range id=rSat value=100></label>
<label>Lightness: <input type=range id=rL max=200 value=100></label>
<label>Use "color" instead: <input type=checkbox id=cColor></label>
</div>
<canvas id=c></canvas>
Global composite operations
The 2D context property ctx.globalCompositeOperation is very useful for a wide range of image processing tasks. For more on globalCompositeOperation at MDN
You can convert the image into a canvas, that way you can edit it.
function imageToCanvas(image){
const c = document.createElement("canvas");
c.width = image.width;
c.height = image.height;
c.ctx = c.getContext("2d"); // attach context to the canvas for eaasy reference
c.ctx.drawImage(image,0,0);
return c;
}
You can use the globalCompositeOperation = "color" to colour the image
function colorImage(image,color){ // image is a canvas image
image.ctx.fillStyle = color;
image.ctx.globalCompositeOperation = "color";
image.ctx.fillRect(0,0,image.width,image.height);
image.ctx.globalCompositeOperation = "source-over";
return image;
}
Unfortunately this also overwrites the alpha pixels so you need to use the original image as a mask to restore the alpha pixels.
function maskImage(dest,source){
dest.ctx.globalCompositeOperation = "destination-in";
dest.ctx.drawImage(source,0,0);
dest.ctx.globalCompositeOperation = "source-over";
return dest;
}
And then you have a coloured image
Example.
In he example I colour the image in a range of colours and added a function to restore the canvas copy of the image back to the original. If you get the image from the page as an element then use naturalWidth and naturalHeight as the width and height properties may not match the image resolution.
const ctx = canvas.getContext("2d");
const image = new Image;
var colCopy;
image.src = "https://i.stack.imgur.com/Kk1qd.png";
image.onload = () => {
colCopy = imageToCanvas(image);
const scale = canvas.height / image.naturalHeight;
ctx.scale(scale, scale);
ctx.drawImage(colCopy, 0, 0);
for (var i = 32; i < 360; i += 32) {
restoreImage(colCopy, image);
colorImage(colCopy, "hsl(" + i + ",100%,50%)");
maskImage(colCopy, image);
ctx.drawImage(colCopy, 150 * i / 16, 0);
}
}
function imageToCanvas(image) {
const c = document.createElement("canvas");
c.width = image.naturalWidth;
c.height = image.naturalHeight;
c.ctx = c.getContext("2d"); // attach context to the canvas for easy reference
c.ctx.drawImage(image, 0, 0);
return c;
}
function restoreImage(dest, source) {
dest.ctx.clearRect(0, 0, dest.width, dest.height);
dest.ctx.drawImage(source, 0, 0);
return dest;
}
function colorImage(dest, color) { // image is a canvas image
dest.ctx.fillStyle = color;
dest.ctx.globalCompositeOperation = "color";
dest.ctx.fillRect(0, 0, dest.width, dest.height);
dest.ctx.globalCompositeOperation = "source-over";
return dest;
}
function maskImage(dest, source) {
dest.ctx.globalCompositeOperation = "destination-in";
dest.ctx.drawImage(source, 0, 0);
dest.ctx.globalCompositeOperation = "source-over";
return dest;
}
canvas {
border: 2px solid black;
}
<canvas id="canvas" width=600></canvas>
The image can get a little washed out in some situations, you can convert the image to a higher contrast black and white image using composite operations similar to shown above, and use the high contrast image as the template to colour.
Using Filters
Most of the common browsers now support canvas filters which has a hue shift filter. You can use that to shift the hue to the value you want, though first you will need to know what the image original hue is. (see below example on how to find HUE)
See Canvas filters at MDN for compatibility and how to use canvas filters.
The following function will preserve the saturation and just shift the hue.
// dest canvas to hold the resulting image
// source the original image
// hue The hue to set the dest image to
// sourceHue the hue reference point of the original image.
function colorImage(dest,source, hue , sourceHue) { // image is a canvas image
dest.ctx.clearRect(0,0,dest.width, dest.height);
dest.ctx.filter="hue-rotate("+((hue - sourceHue) | 0)+"deg)";
dest.ctx.drawImage(source,0, 0, dest.width, dest.height);
return dest;
}
Filters example.
The following uses ctx.filter = "hue-rotate(30deg)" to rotate the hue. I have not included any code to find the image original hue so manually set it by eye to 120.
const ctx = canvas.getContext("2d");
const image = new Image;
var colCopy;
const sourceHue = 120;
image.src = "https://i.stack.imgur.com/Kk1qd.png";
image.onload = () => {
colCopy = imageToCanvas(image);
const scale = canvas.height / image.naturalHeight;
ctx.scale(scale, scale);
ctx.drawImage(colCopy, 0, 0);
for (var i = 32; i < 360; i += 32) {
colorImage(colCopy,image,i,sourceHue);
ctx.drawImage(colCopy, 150 * i / 16, 0);
}
}
function imageToCanvas(image) {
const c = document.createElement("canvas");
c.width = image.naturalWidth;
c.height = image.naturalHeight;
c.ctx = c.getContext("2d"); // attach context to the canvas for easy reference
c.ctx.drawImage(image, 0, 0);
return c;
}
function colorImage(dest,source, hueRotate , sourceHue) { // image is a canvas image
dest.ctx.clearRect(0,0,dest.width, dest.height);
dest.ctx.filter="hue-rotate("+((hueRotate - sourceHue) | 0)+"deg)";
dest.ctx.drawImage(source,0, 0, dest.width, dest.height);
return dest;
}
canvas {
border: 2px solid black;
}
<canvas id="canvas" width=600></canvas>
RGB to Hue
There are plenty of answers to help find the hue of a pixel here on SO. Here is a particularly detailed one RGB to HSL conversion.
Filters example White.
The following uses ctx.filter = "grayscale(100%)" to remove saturation and then ctx.filter = "brightness(amount%)" to change the brightness. This gives a range of gray colours from black to white. You can also do the same with the colour, by reducing the grayscale amount.
const ctx = canvas.getContext("2d");
const image = new Image;
var colCopy;
const sourceHue = 120;
image.src = "https://i.stack.imgur.com/Kk1qd.png";
image.onload = () => {
colCopy = imageToCanvas(image);
const scale = canvas.height / image.naturalHeight;
ctx.scale(scale, scale);
ctx.drawImage(colCopy, 0, 0);
for (var i = 40; i < 240; i += 20) {
grayImage(colCopy,image,i);
ctx.drawImage(colCopy, 150 * ((i-40) / 12), 0);
}
}
function imageToCanvas(image) {
const c = document.createElement("canvas");
c.width = image.naturalWidth;
c.height = image.naturalHeight;
c.ctx = c.getContext("2d"); // attach context to the canvas for easy reference
c.ctx.drawImage(image, 0, 0);
return c;
}
function grayImage(dest,source, brightness) { // image is a canvas image
dest.ctx.clearRect(0,0,dest.width, dest.height);
dest.ctx.filter = "grayscale(100%)";
dest.ctx.drawImage(source,0, 0, dest.width, dest.height);
dest.ctx.filter = "brightness(" + brightness +"%)";
dest.ctx.drawImage(dest,0, 0, dest.width, dest.height);
return dest;
}
canvas {
border: 2px solid black;
}
<canvas id="canvas" width=600></canvas>
You can combine filters on a single line of code before performing your draw operation, like this:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('source');
ctx.filter = 'hue-rotate(120deg) grayscale(10%) brightness(150%)';
ctx.drawImage(image, 10, 10, 180, 120);
<canvas id="canvas"></canvas>
<div style="display:none;">
<img id="source"
src="https://interactive-examples.mdn.mozilla.net/media/examples/gecko-320-213.jpg">
</div>
I'm developing web app using canvas and I made three. canvas, canvas_panorama and canvas_image.
First one is something like main canvas, conteiner for the others. canvas_panorama is a background for canvas_image.
After canvas is right clicked, I'm computing angle to rotate canvas_image:
function getAngle( e, pw /*canvas*/ ){
var offset = pw.offset();
var center_x = (offset.left) + ($(pw).width() / 2);
var center_y = (offset.top) + ($(pw).height() / 2);
var mouse_x = e.pageX;
var mouse_y = e.pageY;
var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
angle = radians;
}
After I have an angle I'm trying to rotate canvas_image like this:
function redraw(){
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect( p1.x, p1.y, p2.x-p1.x, p2.y-p1.y );
canvas_image_ctx.drawImage(image_img, 0, 0, 150, 150);
canvas_panorama_ctx.drawImage(panorama_img, 0, 0, 600, 300);
canvas_panorama_ctx.drawImage(canvas_image, 20, 20);
// rotate panorama_img around its center
// x = x + 0.5 * width
// y = y + 0.5 * height
canvas_panorama_ctx.translate(95, 95);
canvas_panorama_ctx.rotate(angle);
// translate to back
canvas_panorama_ctx.translate(-95, -95);
ctx.drawImage(canvas_panorama, 0, 0);
}
But this rotates both canvas_image and canvas_panorama. It should only rotate canvas_image
JSFiddle to show you my problem
I think you are confusing yourself with this idea of multiple canvases.
Once in the drawImage() method, every of your canvases are just images, and could be just one or even just plain shapes.
Transformation methods do apply to the canvas' context's matrix, and will have effect only if you do some drawing operations when they are set.
Note : To reset your context matrix, you can either use save(); and restore() methods which will also save all other properties of your context, so if you only need to reset the transform, then it's preferred to simply reset the transformation matrix to its default : ctx.setTransform(1,0,0,1,0,0).
Here is a simplified example to make things clearer :
var ctx = canvas.getContext('2d');
// a single shape, with the border of the context matrix
var drawRect = function(){
ctx.beginPath();
ctx.rect(10, 10, 50, 20);
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.stroke();
};
// set the color of our shapes
var gradient = ctx.createLinearGradient(0,0,70,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"yellow");
ctx.fillStyle = gradient;
// here comes the actual drawings
//we don't have modified the transform matrix yet
ctx.strokeStyle = "green";
drawRect();
// here we translate of 100px then we do rotate the context of 45deg
ctx.translate(100, 0)
ctx.rotate(Math.PI/4)
ctx.strokeStyle = "red";
drawRect();
// reset the matrix
ctx.setTransform(1,0,0,1,0,0);
// here we move of 150px to the right and 25px to the bottom
ctx.translate(150, 25)
ctx.strokeStyle = "blue";
drawRect();
// reset the matrix
ctx.setTransform(1,0,0,1,0,0);
<canvas id="canvas" width="500" height="200"></canvas>
In your code, you are setting the transformations on the canvas that does represent your image, and you do draw every of your canvases at each call.
What you want instead, is to set the transformation on the main canvas only, and draw the non-transformed image :
var main_ctx = canvas.getContext('2d');
var img_canvas = canvas.cloneNode();
var bg_canvas = canvas.cloneNode();
var angle = 0;
// draw on the main canvas, and only on the main canvas
var drawToMain = function(){
// first clear the canvas
main_ctx.clearRect(0,0,canvas.width, canvas.height);
// draw the background image
main_ctx.drawImage(bg_canvas, 0,0);
// do the transforms
main_ctx.translate(img_canvas.width/2, img_canvas.height/2);
main_ctx.rotate(angle);
main_ctx.translate(-img_canvas.width/2, -img_canvas.height/2);
// draw the img with the transforms applied
main_ctx.drawImage(img_canvas, 0,0);
// reset the transforms
main_ctx.setTransform(1,0,0,1,0,0);
};
// I changed the event to a simple onclick
canvas.onclick = function(e){
e.preventDefault();
angle+=Math.PI/8;
drawToMain();
}
// a dirty image loader
var init = function(){
var img = (this.src.indexOf('lena')>0);
var this_canvas = img ? img_canvas : bg_canvas;
this_canvas.width = this.width;
this_canvas.height = this.height;
this_canvas.getContext('2d').drawImage(this, 0,0);
if(!--toLoad){
drawToMain();
}
};
var toLoad = 2;
var img = new Image();
img.onload = init;
img.src = "http://pgmagick.readthedocs.org/en/latest/_images/lena_scale.jpg";
var bg = new Image();
bg.onload = init;
bg.src = 'http://www.fnordware.com/superpng/pnggradHDrgba.png';
<canvas id="canvas" width="500" height="300"></canvas>
Normally you can fill a rectangle in a canvas withctx.fillStyle = "whatever color here" and then ctx.fillRect(cords and length and width here). Is there a syntax where I can say ctx.fillRect(someImagePathHere, xOfTopLeft, yofTopLeft)
If not, how else can I achieve this?
The question is ambiguous as there are many ways to "fillRect with an image".
First off images in the browser are downloaded asynchronously so you need to wait for an image to load before you can use it. For canvas situations the most common way to get an image is to create a new Image and set an onload listener
const img = new Image();
img.onload = someFunctionToCallWhenTheImageHasLoaded
img.src = 'http://url/to/image';
Then the question is what do mean by "fillRect"
Using this 256x256 image
For example to draw the image at the size it was downloaded you can use drawImage with 3 arguments
ctx.drawImage(img, x, y);
const img = new Image();
img.onload = draw;
img.src = 'https://i.imgur.com/ZKMnXce.png';
function draw() {
const ctx = document.querySelector('canvas').getContext('2d');
ctx.drawImage(img, 0, 0);
}
canvas { border: 1px solid black; }
<canvas></canvas>
To draw the image at a different size you can use
ctx.drawImage(img, x, y, width, height);
const img = new Image();
img.onload = draw;
img.src = 'https://i.imgur.com/ZKMnXce.png';
function draw() {
const ctx = document.querySelector('canvas').getContext('2d');
const destX = 10;
const destY = 20;
const destWidth = 30;
const destHeight = 40;
ctx.drawImage(img, destX, destY, destWidth, destHeight);
}
canvas { border: 1px solid black; }
<canvas></canvas>
To draw part of the image you can use
// part of image to draw
const srcX = 10;
const srcY = 20;
const srcWidth = 130;
const srcHeight = 140;
// where to draw it
const dstX = 60;
const dstY = 70;
const dstWidth = 160;
const dstHeight = 40;
ctx.drawImage(img, srcX, srcY, srcWidth, srcHeight,
dstX, dstY, dstWidth, dstHeight);
const img = new Image();
img.onload = draw;
img.src = 'https://i.imgur.com/ZKMnXce.png';
function draw() {
const ctx = document.querySelector('canvas').getContext('2d');
// part of image to draw
const srcX = 10;
const srcY = 20;
const srcWidth = 130;
const srcHeight = 140;
// where to draw it
const dstX = 60;
const dstY = 70;
const dstWidth = 160;
const dstHeight = 40;
ctx.drawImage(img, srcX, srcY, srcWidth, srcHeight,
dstX, dstY, dstWidth, dstHeight);
}
canvas { border: 1px solid black; }
<canvas></canvas>
That said, "fillRect" being ambiguous maybe you wanted to use the image as a pattern in which case you need to make a pattern out of it using createPattern
const pattern = ctx.createPatttern(img, 'repeat');
For these let's use this 16x16 pixel image
You can then use the pattern as your fillStyle as in
ctx.fillStyle = pattern;
ctx.fillRect(10, 20, 30, 40);
const img = new Image();
img.onload = draw;
img.src = 'https://i.imgur.com/fqgm8uh.png';
function draw() {
const ctx = document.querySelector('canvas').getContext('2d');
const pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(10, 20, 30, 40);
}
canvas { border: 1px solid black; }
<canvas></canvas>
Patterns are relative to the origin of the canvas which means if you just use ctx.fillRect (or any other fill) the pattern will match across fills.
ctx.fillRect(10, 20, 30, 40);
ctx.beginPath();
ctx.arc(50, 60, 25, 0, Math.PI * 2);
ctx.fill();
const img = new Image();
img.onload = draw;
img.src = 'https://i.imgur.com/fqgm8uh.png';
function draw() {
const ctx = document.querySelector('canvas').getContext('2d');
const pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(10, 20, 30, 40);
ctx.beginPath();
ctx.arc(50, 60, 25, 0, Math.PI * 2);
ctx.fill();
}
canvas { border: 1px solid black; }
<canvas></canvas>
Because patterns are anchored at the origin if you are animating without changing the origin you'll notice the pattern doesn't move
const img = new Image();
img.onload = start;
img.src = 'https://i.imgur.com/fqgm8uh.png';
function start() {
const ctx = document.querySelector('canvas').getContext('2d');
const pattern = ctx.createPattern(img, 'repeat');
function render(time) {
time *= 0.001; // seconds;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const x = Math.sin(time * 1.1) * 150 + 150;
const y = Math.sin(time * 1.2) * 50 + 50;
ctx.fillStyle = pattern;
ctx.fillRect(x, y, 30, 40);
ctx.beginPath();
ctx.arc(x, y, 25, 0, Math.PI * 2);
ctx.fill();
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
canvas { border: 1px solid black; }
<canvas></canvas>
In order to move the pattern you need to move the origin of the canvas using ctx.translate (as well as ctx.rotate, ctx.scale, ctx.setTransform)
const img = new Image();
img.onload = start;
img.src = 'https://i.imgur.com/fqgm8uh.png';
function start() {
const ctx = document.querySelector('canvas').getContext('2d');
const pattern = ctx.createPattern(img, 'repeat');
function render(time) {
time *= 0.001; // seconds;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const x = Math.sin(time * 1.1) * 150 + 150;
const y = Math.sin(time * 1.2) * 50 + 50;
ctx.translate(x, y);
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 30, 40);
ctx.beginPath();
ctx.arc(0, 0, 25, 0, Math.PI * 2);
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0); // set it back to the default
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
canvas { border: 1px solid black; }
<canvas></canvas>
Here's an illustration of some of the possibilities:
var im = new Image();
im.src = "https://upload.wikimedia.org/wikipedia/commons/7/79/Face-smile.svg";
im.onload = function () { /* first, wait until the image is loaded */
/* create five canvases, and draw something in each */
for (var i=1; i<=5; i++) {
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = canvas.height = 200;
var ctx=canvas.getContext("2d");
var x=50, y=50; /* where to plot */
var w=20, h=60; /* width and height of rectangle, if applicable */
switch (i) {
case 1:
/* first canvas: draw a rectangle */
ctx.fillRect(x, y, w, h);
break;
case 2:
/* second canvas: draw an image, actual size, no clipping */
/* coordinates are where the top left of the image is plotted */
ctx.drawImage(im, x, y);
break;
case 3:
/* third canvas: draw an image, scaled to rectangle */
ctx.drawImage(im, x, y, w, h);
break;
case 4:
/* fourth canvas: draw an image, actual size, clipped to rectangle */
ctx.save();
ctx.rect(x, y, w, h);
ctx.clip();
ctx.drawImage(im, x, y);
ctx.restore();
break;
case 5:
/* fifth canvas: draw shapes filled with a background image */
ctx.fillStyle = ctx.createPattern(im, 'repeat'); /* or 'no-repeat', or 'repeat-x', or 'repeat-y' */
/* note that the image is tiled from the top left of the canvas */
ctx.fillRect(x, y, w, h);
/* also draw a circle, why not */
ctx.beginPath();
ctx.arc(150, 150, 40, 0, Math.PI*2);
ctx.fill();
break;
}
}
}
im.onerror = function() { alert("failed to load image"); };
Jsfiddle: http://jsfiddle.net/efeqjjno/
Here is a quick example of how you can use drawImage to draw an image to a canvas. The element on the left is the image, the element on the right is the canvas with the image drawn on it.
JSFiddle: https://jsfiddle.net/gw8ncg7g/
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("image");
ctx.drawImage(img, 0, 0);
}
canvas {
border:1px solid #d3d3d3;
}
<img id="image" width="300" height="300" src="http://i.imgur.com/LDR6AWn.png?1">
<canvas id="myCanvas" width="300" height="300" >
StackOverflow community, I'm fairly new to JavaScript programming and I'm having some issues with the HTML5/JavaScript Canvas Combo.
The idea is to, following the click of a button, to verify some lines and, then, show on the screen the image (pre-defined) with some text in specific coordinates, the text depends on the input value, as they are stored in an Array.
The thing is, I'm not being able to draw the text on the Image, only the Image appears. The code goes as follows:
Globally Defined:
...
canvas = document.getElementById("cvs"),
ctx = canvas.getContext('2d'),
...
The Draw() function:
function draw() {
if (img_is_loaded) {
img = document.getElementById("background-A");
var maxh = 600,
maxw = 900,
height = img.height,
width = img.width,
name_input = name[0],
note_input = note[0],
date_input = date[0],
sur_input = sur[0];
while (height > maxh || width > maxw) {
--height;
--width;
}
canvas.height = height;
canvas.width = width;
ctx.save();
ctx.clearRect(0, 0, width, height);
ctx.drawImage(img, 0, 0, width, height);
ctx.font = "54px Times Roman";
ctx.fillStyle = "#000000";
ctx.fillText = (name_input, 35, 320);
ctx.font = "21px Times Roman";
ctx.fillStyle = "#000000";
ctx.fillText = (note_input, 61, 432);
ctx.fillText = (date_input, 254, 501);
ctx.fillText = (sur_input, 254, 528);
}
} else {
setTimeout(draw, 100);
}
}
I'm getting the Image, but no text. I'm aware that the issue, normally, is that I need to draw them "at the same time", so I tried:
function draw() {
if (img_is_loaded) {
var imageObj = new Image();
imageObj.onload = function(){
var maxh = 600,
maxw = 900,
height = imageObj.height,
width = imageObj.width,
name_input = name[0],
note_input = note[0],
date_input = date[0],
sur_input = sur[0];
while (height > maxh || width > maxw) {
--height;
--width;
}
canvas.height = height;
canvas.width = width;
ctx.save();
ctx.clearRect(0, 0, width, height);
$('#spinner-generate').hide();
ctx.drawImage(imageObj, 0, 0, width, height);
ctx.font = "54px Times Roman";
ctx.fillStyle = "#000000";
ctx.fillText = (name_input, 35, 320);
ctx.font = "21px Times Roman";
ctx.fillStyle = "#000000";
ctx.fillText = (note_input, 61, 432);
ctx.fillText = (date_input, 254, 501);
ctx.fillText = (sur_input, 254, 528);
ctx.restore();
}
imageObj.src = "IMAGEPATH";
} else {
setTimeout(draw, 100);
}
}
But, in this case, the "imageObj.onload" function gets skipped by the code, that automatically jumps to "else".
I'm really confused at this point, since every source I consulted says that it is "simple" and uses the imageObj.onload example, but with the "window.onload" combination.
Is there something I'm missing regarding the Canvas' "Order of things"?
I appreciate and thank in advance for any response or input.
You're using fillText as a property while it should have been used as a method - simply change the lines to this format:
ctx.fillText(name_input, 35, 320);
I did not check the rest of the code.