Canvas 'Clip' reverse action? - html

Assuming I have:
var context = document.getElementById('test').getContext('2d');
// Background
context.fillStyle = '#000';
context.fillRect(0,0,300,300);
// 'P'
context.beginPath();
context.moveTo(90,89);
context.lineTo(161,89);
context.quadraticCurveTo(200,89,200,127);
context.quadraticCurveTo(200,166,148,166);
context.lineTo(115,166);
context.lineTo(108,210);
context.lineTo(69,210);
context.lineTo(90,89);
context.fillStyle = "#eee";
context.fill();
context.closePath();
context.globalCompositeOperation = 'destination-out';
// 'P' hole
context.beginPath();
context.moveTo(124,117);
context.lineTo(146,117);
context.quadraticCurveTo(160,117,160,127);
context.quadraticCurveTo(160,145,146,145);
context.lineTo(120,145);
context.lineTo(124,117);
context.fillStyle = '#ffffff';
context.fill();
context.closePath();
This works, except as you can see the 'hole' isn't a clip, so if the background isn't solid, you simply can't set the 'fill' color of the hole to match the background.
Therefore I need to clip the hole instead. When I do that however, the only part of the 'P' that shows is the part bound by the clip 'hole'. I need the reverse. I need the 'P' to show, but clip the part with the 'hole' so any background will show through.
Here is as far as I got, but not quite there:
var context = document.getElementById('test').getContext('2d');
// Background
context.fillStyle = '#000';
context.fillRect(0,0,300,300);
// 'P' hole clip
context.beginPath();
context.moveTo(124,117);
context.lineTo(146,117);
context.quadraticCurveTo(160,117,160,127);
context.quadraticCurveTo(160,145,146,145);
context.lineTo(120,145);
context.lineTo(124,117);
context.clip();
context.closePath();
// 'P'
context.beginPath();
context.moveTo(90,89);
context.lineTo(161,89);
context.quadraticCurveTo(200,89,200,127);
context.quadraticCurveTo(200,166,148,166);
context.lineTo(115,166);
context.lineTo(108,210);
context.lineTo(69,210);
context.lineTo(90,89);
context.fillStyle = "#eee";
context.fill();
context.closePath();
Thank you for your help!

I understand you asked this a while ago but I have an answer for you.
Your first example was half-correct. Using destination-out will work, however in order not to disturb the canvas you want to draw on, we create a new canvas and draw it in that.
Then once we've drawn our shape on there with our cutaways, we then draw the entire canvas onto the original. Since the new canvas has no background it will keep transparency.
var canvas = document.getElementById('test'),
context = canvas.getContext('2d'),
// New canvas - we will draw the letter P on here
newCanvas = document.createElement('canvas'),
newContext = newCanvas.getContext('2d');
// Make sure you have enough room on your new canvas
newCanvas.width = canvas.width;
newCanvas.height = canvas.height;
with(newContext) {
// 'P'
beginPath();
moveTo(90,89);
lineTo(161,89);
quadraticCurveTo(200,89,200,127);
quadraticCurveTo(200,166,148,166);
lineTo(115,166);
lineTo(108,210);
lineTo(69,210);
lineTo(90,89);
fillStyle = "#eee";
fill();
closePath();
globalCompositeOperation = 'destination-out';
// 'P' hole
beginPath();
moveTo(124,117);
lineTo(146,117);
quadraticCurveTo(160,117,160,127);
quadraticCurveTo(160,145,146,145);
lineTo(120,145);
lineTo(124,117);
fillStyle = '#000';
fill();
closePath();
}
with(context) {
// Background
fillStyle = '#000';
fillRect(0,0,300,300);
// Simply reference the canvas element when drawing
drawImage(newCanvas, 0, 0);
}

I know this is very old but... you are not using clip correctly in your second try. Everything that comes after clip will be drawn only on the clipped area.
so you could either:
Clip the hole and redraw the background
var context = document.getElementById('test').getContext('2d');
// Background
context.fillStyle = '#000';
context.fillRect(0,0,300,300);
// 'P'
context.beginPath();
context.moveTo(90,89);
context.lineTo(161,89);
context.quadraticCurveTo(200,89,200,127);
context.quadraticCurveTo(200,166,148,166);
context.lineTo(115,166);
context.lineTo(108,210);
context.lineTo(69,210);
context.lineTo(90,89);
context.fillStyle = "#eee";
context.fill();
// 'P' hole clip
context.beginPath();
context.moveTo(124,117);
context.lineTo(146,117);
context.quadraticCurveTo(160,117,160,127);
context.quadraticCurveTo(160,145,146,145);
context.lineTo(120,145);
context.lineTo(124,117);
context.clip();
// Redraw Background in the clipped area
context.fillStyle = '#000';
context.fillRect(0,0,300,300);
<canvas id="test" width="300" height="300">
clip the outside part of the hole and draw the P
var context = document.getElementById('test').getContext('2d');
// Background
context.fillStyle = '#000';
context.fillRect(0,0,300,300);
// inverse 'P' hole clip
context.beginPath();
context.rect(0, 0, 300, 300);
context.lineTo(124,117);
context.lineTo(120,145);
context.lineTo(146,145);
context.quadraticCurveTo(160,145,160,127);
context.quadraticCurveTo(160,117,146,117);
context.lineTo(124,117);
context.clip();
// 'P'
context.beginPath();
context.moveTo(90,89);
context.lineTo(161,89);
context.quadraticCurveTo(200,89,200,127);
context.quadraticCurveTo(200,166,148,166);
context.lineTo(115,166);
context.lineTo(108,210);
context.lineTo(69,210);
context.lineTo(90,89);
context.fillStyle = "#eee";
context.fill();
<canvas id="test" width="300" height="300">
Also, you don't need to use closePath here.

Related

html5 canvas text slide in behind nothing

I want to have html5 canvas text slide in behind nothing, its an effect where text appears like coming out behind some obstacle, but the obstacle is invisible.
Here is some youtube video showing how to do it in after effect:
https://www.youtube.com/watch?v=KIYMy7vLLRo
I know how to slide a text along canvas, and one idea I got is having two canvases on top of each other, and top canvas is smaller and contains the text that is initially out of canvas and slides in. But if there is a way to do it with just one canvas that would be great.
You can using a clipping path to mask out part of the text.
Save the existing clipping path using the save() method. Create a shape/path and make it the new clipping path using the clip() method. Draw your text. Store the previous clipping path using the restore() method.
For example, suppose your canvas is 100 pixels by 100 pixels. The following will draw text on only the left side of the canvas.
context.save();
context.rect(0, 0, 50, 100);
context.clip();
context.fillText("Draw some text.", 30, 50);
context.restore();
jsFiddle : https://jsfiddle.net/CanvasCode/vgpov2yk/3
var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
// Positions for the text startint off
var xText = -100;
var yText = 150;
// This will update the canvas as fast as possible (not good)
setInterval(function () {
// Clear the canvas
ctx.fillStyle = "#F0F";
ctx.fillRect(0, 0, c.width, c.height);
ctx.save()
// We create a clip rect
ctx.rect(200,0,400,400);
ctx.clip();
// Draw text
ctx.fillStyle = "#FFF";
ctx.font = "30px Arial";
ctx.fillText("Hello World", xText, yText);
ctx.restore();
// Increase the text x position
if (xText < 200) {
xText += 0.5;
}
}, 15);
All you have to do is use a clip rect which is like a mask in image editing.

HTML5 CANVAS Shadow a bug? or a code defect?

I'm faced with the problem about drawing of canvas.
Canvas is saved to data:image once.
And it is made to redraw.
Two problems occur at this time.
A shadow will be applied to the object which has not drawn the shadow.
A shadow will become deep if save and a redraw are repeated.
<canvas id="SAMPLE" width="960" height="480"></canvas>
<script type="text/javascript" src="./jquery.js"></script>
<script>
var canvas = $("#SAMPLE"),
ctx = canvas[0].getContext("2d");
// first object (no shadow)
ctx.strokeStyle = "#0067ef";
ctx.fillStyle = "#0067ef";
ctx.lineCap = "round";
ctx.lineWidth = "15";
ctx.globalAlpha = 1;
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowColor = "#363636";
ctx.beginPath();
ctx.moveTo( 10, 10);
ctx.lineTo(200, 200);
ctx.stroke();
ctx.closePath();
// second object (has shadow)
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowColor = "#363636";
ctx.beginPath();
ctx.moveTo(300, 10);
ctx.lineTo(400, 200);
ctx.stroke();
ctx.closePath();
// Canvas is saved to data:image once.
var save = canvas[0].toDataURL();
// clear canvas
ctx.clearRect(0, 0, 960, 480);
// redraw
var img = new Image();
img.src = save;
img.onload = function() {
ctx.drawImage(this,0,0);
};
</script>
It was normal when the picture at the time of save and before a redraw was investigated.
Two problems occur at the time of a redraw.
A shadow will be applied to the object which has not drawn the shadow.
A shadow will become deep if save and a redraw are repeated.
Does my code have a defect?
Because your fillStyle and other parameters are preserved, so upon drawing image, the effect is stacking up.
Use save() and restore() to prevent this:
ctx.save();
// first object (no shadow)
ctx.strokeStyle = "#0067ef";
ctx.fillStyle = "#0067ef";
/*
...
*/
ctx.closePath();
ctx.restore();
// Canvas is saved to data:image once.
JSFiddle demo with one extra canvas and the appended image for comparison.
Comment out the save() and restore() and re-run the fiddle, you'll notice the different.

A smooth circle in Html5

I'm trying to draw a circle with a canvas in HTML5. I use an example from w3schools, but the result is ugly, not smooth. Is it possible to have a smooth circle ? (I tried this with Chrome and IE9)
The code I use :
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(125,120,100,0,2*Math.PI);
ctx.stroke();
=> http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_tut_path2 : the original example
=> http://jsfiddle.net/jPeKk/ : my try, bigger
On chrome, this is a known issue that has been discussed here - Can I turn off antialiasing on an HTML <canvas> element?
and here - How to anti-alias clip() edges in html5 canvas under Chrome Windows?
Try
ctx.webkitImageSmoothingEnabled=true;
to make your line smoother.
Another solution that works for me (though I think it's more of a hack than a proper solution) is to draw a line around the circle with the same color. For some reason this is going to be very smooth.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(100, 100, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#775599';
context.fill();
context.beginPath();
context.arc(200, 200, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#775599';
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#775599';
context.stroke();

Draw single pixel line in html5 canvas

When i try to draw single pixel black line with the following code:
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineWidth = 1;
context.stroke();
context.closePath();
I have more then one pixel line with gray border. How to fix it?
Here is an example http://jsfiddle.net/z4VJq/
Call your function with these coordinates instead: drawLine(30,30.5,300,30.5);. Try it in jsFiddle.
The problem is that your color will be at an edge, so the color will be halfway in the pixel above the edge and halfway below the edge. If you set the position of the line in the middle of an integer, it will be drawn within a pixel line.
This picture (from the linked article below) illustrates it:
You can read more about this on Canvas tutorial: A lineWidth example.
You have to use context.translate(.5,.5); to offset everything by half a pixel. Its easy way for fix your problem
var canvas = document.getElementById("canvas1");
var context1 = canvas.getContext('2d');
context1.strokeStyle = '#000';
context1.beginPath();
context1.moveTo(10, 5);
context1.lineTo(300, 5);
context1.stroke();
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
context2.translate(.5,.5);
context2.strokeStyle = '#000';
context2.beginPath();
context2.moveTo(10, 5);
context2.lineTo(300, 5);
context2.stroke();
<div><canvas height='10' width='300' id='canvas1'>Обновите браузер</canvas></div>
<div><canvas height='10' width='300' id='canvas2'>Обновите браузер</canvas></div>

HTML5 - Canvas Shape Stroke

I have created 2 shapes, circle and rectangle, one on top of the other to resemble a key lock. I then try to apply a stroke but its stroking both shapes. What I want it to do is just stroke the merged pattern and not any of the intersections.
context.beginPath();
context.fillStyle = "#ccc";
context.arc(115, 550, 12, 0, 2 * Math.PI, false);
context.moveTo(105, 555);
context.fillStyle = "#999";
context.rect(105, 555, 20, 30);
context.fill();
context.stroke();
context.closePath();
If I try to draw the rect first, then the arc on top there are extra line paths when you stroke, its like I have to close Path and then draw it again.
You can't use a rect and a whole circle if you want the path to do without the intersecting part.
Instead you have to draw only part of the circle and only part of the rectangle. This should do it for you:
context.beginPath();
context.fillStyle = "#ccc";
context.arc(115, 550, 12, 2.5, 2.2 * Math.PI, false);
context.moveTo(105+20, 555);
context.fillStyle = "#999";
// instead of a rect, we really want three lines
context.lineTo(105+20,555+30);
context.lineTo(105,555+30);
context.lineTo(105,555);
context.fill();
context.stroke();
context.closePath();
While working on my own irregular shape answer, I discovered a lab project by Professor Cloud that solved my problem.
This page, SVG-to-Canvas, parses an SVG graphic to Canvas code. So if you have an application like Illustrator with which you can draw and save the graphic as SVG, then you can parse the usable canvas codes and just plug them in.
You can use compositing and temporary canvas. Something like that:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var tempCanvas = document.getElementById('tempCanvas');
var tempContext = tempCanvas.getContext('2d');
tempContext.save();
// clear temp context
tempContext.clearRect(0, 0, canvas.width, canvas.height);
// draw all rects with strokes
tempContext.beginPath();
tempContext.strokeStyle='red';
tempContext.lineWidth=3;
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false);
tempContext.rect(20,150,100,200);
tempContext.stroke();
// set compositing to erase existing drawings
// where the new drawings are drawn
tempContext.globalCompositeOperation='destination-out';
// fill all rects
// This "erases" all but the outline stroke
tempContext.beginPath();
tempContext.fillStyle='blue';
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false);
tempContext.rect(20,150,100,200);
tempContext.fill();
// draw outlines from tempcanvas into canvas
ctx.drawImage(tempCanvas, 0, 0);
// draw into canvas
ctx.beginPath();
ctx.fillStyle='green';
ctx.globalAlpha = 0.2;
ctx.rect(20,150,100,200);
ctx.arc(100, 100, 60, 0, 2 * Math.PI, false);
ctx.fill();
tempContext.restore();
And a jsfiddle: https://jsfiddle.net/EvaF/8to68dtd/2/